author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
339,410
19.01.2022 12:18:53
-3,600
e2ac7b38f4eeb395896fe2f0bd39f8e57bc1b1a6
Adding missing database constraints for clients in JPA map storage. This should ensure consistency for the store even in the event of concurrent creation of clients by multiple callers. Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "diff": "@@ -36,6 +36,7 @@ import javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n+import javax.persistence.UniqueConstraint;\nimport javax.persistence.Version;\nimport org.hibernate.annotations.Type;\nimport org.hibernate.annotations.TypeDef;\n@@ -52,7 +53,12 @@ import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n* therefore marked as non-insertable and non-updatable to instruct hibernate.\n*/\n@Entity\n-@Table(name = \"client\")\n+@Table(name = \"client\",\n+ uniqueConstraints = {\n+ @UniqueConstraint(\n+ columnNames = {\"realmId\", \"clientId\"}\n+ )\n+})\n@TypeDefs({@TypeDef(name = \"jsonb\", typeClass = JsonbType.class)})\npublic class JpaClientEntity extends AbstractClientEntity implements Serializable {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "diff": "@@ -44,7 +44,7 @@ limitations under the License.\n<createIndex tableName=\"client\" indexName=\"client_entityVersion\">\n<column name=\"entityversion\"/>\n</createIndex>\n- <createIndex tableName=\"client\" indexName=\"client_realmId_clientId\">\n+ <createIndex tableName=\"client\" indexName=\"client_realmId_clientId\" unique=\"true\">\n<column name=\"realmid\"/>\n<column name=\"clientid\"/>\n</createIndex>\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/client/MapClientProvider.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/client/MapClientProvider.java", "diff": "@@ -139,15 +139,19 @@ public class MapClientProvider implements ClientProvider {\npublic ClientModel addClient(RealmModel realm, String id, String clientId) {\nLOG.tracef(\"addClient(%s, %s, %s)%s\", realm, id, clientId, getShortStackTrace());\n+ if (id != null && tx.read(id) != null) {\n+ throw new ModelDuplicateException(\"Client with same id exists: \" + id);\n+ }\n+ if (clientId != null && getClientByClientId(realm, clientId) != null) {\n+ throw new ModelDuplicateException(\"Client with same clientId in realm \" + realm.getName() + \" exists: \" + clientId);\n+ }\n+\nMapClientEntity entity = new MapClientEntityImpl();\nentity.setId(id);\nentity.setRealmId(realm.getId());\nentity.setClientId(clientId);\nentity.setEnabled(true);\nentity.setStandardFlowEnabled(true);\n- if (id != null && tx.read(id) != null) {\n- throw new ModelDuplicateException(\"Client exists: \" + id);\n- }\nentity = tx.create(entity);\nif (clientId == null) {\nclientId = entity.getId();\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Adding missing database constraints for clients in JPA map storage. This should ensure consistency for the store even in the event of concurrent creation of clients by multiple callers. Closes #9610
339,364
11.01.2022 14:36:43
-3,600
6b485b8603610e33be63069881a9806dc0ba424e
Baseline for Keycloak deployment in operator
[ { "change_type": "ADD", "old_path": null, "new_path": "operator/src/main/java/org/keycloak/operator/Config.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.operator;\n+\n+import io.smallrye.config.ConfigMapping;\n+\n+/**\n+ * @author Vaclav Muzikar <[email protected]>\n+ */\n+@ConfigMapping(prefix = \"operator\")\n+public interface Config {\n+ Keycloak keycloak();\n+\n+ interface Keycloak {\n+ String image();\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/Constants.java", "new_path": "operator/src/main/java/org/keycloak/operator/Constants.java", "diff": "@@ -28,9 +28,11 @@ public final class Constants {\npublic static final String MANAGED_BY_VALUE = \"keycloak-operator\";\npublic static final Map<String, String> DEFAULT_LABELS = Map.of(\n- \"app\", NAME\n+ \"app\", NAME,\n+ MANAGED_BY_LABEL, MANAGED_BY_VALUE\n);\n- public static final String DEFAULT_KEYCLOAK_IMAGE = \"quay.io/keycloak/keycloak-x:latest\";\n- public static final String DEFAULT_KEYCLOAK_INIT_IMAGE = \"quay.io/keycloak/keycloak-init-container:latest\";\n+ public static final Map<String, String> DEFAULT_DIST_CONFIG = Map.of(\n+ \"KEYCLOAK_METRICS_ENABLED\", \"true\"\n+ );\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/main/java/org/keycloak/operator/OperatorManagedResource.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.operator;\n+\n+import io.fabric8.kubernetes.api.model.HasMetadata;\n+import io.fabric8.kubernetes.api.model.OwnerReference;\n+import io.fabric8.kubernetes.api.model.OwnerReferenceBuilder;\n+import io.fabric8.kubernetes.client.CustomResource;\n+import io.fabric8.kubernetes.client.KubernetesClient;\n+import io.quarkus.logging.Log;\n+\n+import java.util.Collections;\n+import java.util.HashMap;\n+import java.util.Map;\n+import java.util.Optional;\n+\n+/**\n+ * Represents a single K8s resource that is managed by this operator (e.g. Deployment, Service, Ingress, etc.)\n+ *\n+ * @author Vaclav Muzikar <[email protected]>\n+ */\n+public abstract class OperatorManagedResource {\n+ protected KubernetesClient client;\n+ protected CustomResource<?, ?> cr;\n+\n+ public OperatorManagedResource(KubernetesClient client, CustomResource<?, ?> cr) {\n+ this.client = client;\n+ this.cr = cr;\n+ }\n+\n+ protected abstract HasMetadata getReconciledResource();\n+\n+ public void createOrUpdateReconciled() {\n+ HasMetadata resource = getReconciledResource();\n+ setDefaultLabels(resource);\n+ setOwnerReferences(resource);\n+\n+ Log.debugf(\"Creating or updating resource: %s\", resource);\n+ resource = client.resource(resource).createOrReplace();\n+ Log.debugf(\"Successfully created or updated resource: %s\", resource);\n+ }\n+\n+ protected void setDefaultLabels(HasMetadata resource) {\n+ Map<String, String> labels = Optional.ofNullable(resource.getMetadata().getLabels()).orElse(new HashMap<>());\n+ labels.putAll(Constants.DEFAULT_LABELS);\n+ resource.getMetadata().setLabels(labels);\n+ }\n+\n+ protected void setOwnerReferences(HasMetadata resource) {\n+ if (!cr.getMetadata().getNamespace().equals(resource.getMetadata().getNamespace())) {\n+ return;\n+ }\n+\n+ OwnerReference owner = new OwnerReferenceBuilder()\n+ .withApiVersion(cr.getApiVersion())\n+ .withKind(cr.getKind())\n+ .withName(cr.getMetadata().getName())\n+ .withUid(cr.getMetadata().getUid())\n+ .withBlockOwnerDeletion(true)\n+ .withController(true)\n+ .build();\n+\n+ resource.getMetadata().setOwnerReferences(Collections.singletonList(owner));\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/KeycloakController.java", "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/KeycloakController.java", "diff": "@@ -18,59 +18,101 @@ package org.keycloak.operator.v2alpha1;\nimport javax.inject.Inject;\n+import io.fabric8.kubernetes.api.model.OwnerReference;\n+import io.fabric8.kubernetes.api.model.apps.Deployment;\nimport io.fabric8.kubernetes.client.KubernetesClient;\n-import io.javaoperatorsdk.operator.api.reconciler.*;\n-import io.javaoperatorsdk.operator.api.reconciler.Constants;\n-import org.jboss.logging.Logger;\n+import io.fabric8.kubernetes.client.informers.SharedIndexInformer;\n+import io.javaoperatorsdk.operator.api.reconciler.Context;\n+import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;\n+import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusHandler;\n+import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext;\n+import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer;\n+import io.javaoperatorsdk.operator.api.reconciler.Reconciler;\n+import io.javaoperatorsdk.operator.api.reconciler.RetryInfo;\n+import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;\n+import io.javaoperatorsdk.operator.processing.event.ResourceID;\n+import io.javaoperatorsdk.operator.processing.event.source.EventSource;\n+import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource;\n+import io.quarkus.logging.Log;\n+import org.keycloak.operator.Config;\n+import org.keycloak.operator.Constants;\nimport org.keycloak.operator.v2alpha1.crds.Keycloak;\nimport org.keycloak.operator.v2alpha1.crds.KeycloakStatus;\n+import org.keycloak.operator.v2alpha1.crds.KeycloakStatusBuilder;\n-@ControllerConfiguration(namespaces = Constants.WATCH_CURRENT_NAMESPACE, finalizerName = Constants.NO_FINALIZER)\n-public class KeycloakController implements Reconciler<Keycloak> {\n+import java.util.Collections;\n+import java.util.List;\n+import java.util.Optional;\n+import java.util.Set;\n- @Inject\n- Logger logger;\n+import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE;\n+\n+@ControllerConfiguration(namespaces = WATCH_CURRENT_NAMESPACE)\n+public class KeycloakController implements Reconciler<Keycloak>, EventSourceInitializer<Keycloak>, ErrorStatusHandler<Keycloak> {\n@Inject\nKubernetesClient client;\n+ @Inject\n+ Config config;\n+\n+ @Override\n+ public List<EventSource> prepareEventSources(EventSourceContext<Keycloak> context) {\n+ SharedIndexInformer<Deployment> deploymentInformer =\n+ client.apps().deployments().inAnyNamespace()\n+ .withLabels(Constants.DEFAULT_LABELS)\n+ .runnableInformer(0);\n+\n+ EventSource deploymentEvent = new InformerEventSource<>(\n+ deploymentInformer, d -> {\n+ List<OwnerReference> ownerReferences = d.getMetadata().getOwnerReferences();\n+ if (!ownerReferences.isEmpty()) {\n+ return Set.of(new ResourceID(ownerReferences.get(0).getName(), d.getMetadata().getNamespace()));\n+ } else {\n+ return Collections.emptySet();\n+ }\n+ });\n+\n+ return List.of(deploymentEvent);\n+ }\n+\n@Override\npublic UpdateControl<Keycloak> reconcile(Keycloak kc, Context context) {\n- logger.trace(\"Reconcile loop started\");\n- final var spec = kc.getSpec();\n+ String kcName = kc.getMetadata().getName();\n+ String namespace = kc.getMetadata().getNamespace();\n- logger.info(\"Reconciling Keycloak: \" + kc.getMetadata().getName() + \" in namespace: \" + kc.getMetadata().getNamespace());\n+ Log.infof(\"--- Reconciling Keycloak: %s in namespace: %s\", kcName, namespace);\n- KeycloakStatus status = kc.getStatus();\n- var deployment = new KeycloakDeployment(client);\n+ var statusBuilder = new KeycloakStatusBuilder();\n- try {\n- var kcDeployment = deployment.getKeycloakDeployment(kc);\n+ // TODO use caches in secondary resources; this is a workaround for https://github.com/java-operator-sdk/java-operator-sdk/issues/830\n+ // KeycloakDeployment deployment = new KeycloakDeployment(client, config, kc, context.getSecondaryResource(Deployment.class).orElse(null));\n+ var kcDeployment = new KeycloakDeployment(client, config, kc, null);\n+ kcDeployment.updateStatus(statusBuilder);\n+ kcDeployment.createOrUpdateReconciled();\n- if (kcDeployment == null) {\n- // Need to create the deployment\n- deployment.createKeycloakDeployment(kc);\n- }\n+ var status = statusBuilder.build();\n- var nextStatus = deployment.getNextStatus(spec, status, kcDeployment);\n+ Log.info(\"--- Reconciliation finished successfully\");\n- if (!nextStatus.equals(status)) {\n- logger.trace(\"Updating the status\");\n- kc.setStatus(nextStatus);\n- return UpdateControl.updateStatus(kc);\n- } else {\n- logger.trace(\"Nothing to do\");\n+ if (status.equals(kc.getStatus())) {\nreturn UpdateControl.noUpdate();\n}\n- } catch (Exception e) {\n- logger.error(\"Error reconciling\", e);\n- status = new KeycloakStatus();\n- status.setMessage(\"Error performing operations:\\n\" + e.getMessage());\n- status.setState(KeycloakStatus.State.ERROR);\n- status.setError(true);\n-\n+ else {\nkc.setStatus(status);\nreturn UpdateControl.updateStatus(kc);\n}\n}\n+\n+ @Override\n+ public Optional<Keycloak> updateErrorStatus(Keycloak kc, RetryInfo retryInfo, RuntimeException e) {\n+ Log.error(\"--- Error reconciling\", e);\n+ KeycloakStatus status = new KeycloakStatusBuilder()\n+ .addErrorMessage(\"Error performing operations:\\n\" + e.getMessage())\n+ .build();\n+\n+ kc.setStatus(status);\n+\n+ return Optional.of(kc);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/KeycloakDeployment.java", "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/KeycloakDeployment.java", "diff": "*/\npackage org.keycloak.operator.v2alpha1;\n+import io.fabric8.kubernetes.api.model.Container;\n+import io.fabric8.kubernetes.api.model.EnvVarBuilder;\n+import io.fabric8.kubernetes.api.model.HasMetadata;\nimport io.fabric8.kubernetes.api.model.apps.Deployment;\nimport io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;\nimport io.fabric8.kubernetes.client.KubernetesClient;\n+import io.quarkus.logging.Log;\n+import org.keycloak.operator.Config;\n+import org.keycloak.operator.Constants;\n+import org.keycloak.operator.OperatorManagedResource;\nimport org.keycloak.operator.v2alpha1.crds.Keycloak;\n-import org.keycloak.operator.v2alpha1.crds.KeycloakSpec;\n-import org.keycloak.operator.v2alpha1.crds.KeycloakStatus;\n+import org.keycloak.operator.v2alpha1.crds.KeycloakStatusBuilder;\nimport java.net.URL;\n+import java.util.HashMap;\n+import java.util.Optional;\n+import java.util.stream.Collectors;\n-import static org.keycloak.operator.v2alpha1.crds.KeycloakStatus.State.*;\n+public class KeycloakDeployment extends OperatorManagedResource {\n-public class KeycloakDeployment {\n+// public static final Pattern CONFIG_SECRET_PATTERN = Pattern.compile(\"^\\\\$\\\\{secret:([^:]+):(.+)}$\");\n- KubernetesClient client = null;\n+ private final Config config;\n+ private final Keycloak keycloakCR;\n+ private final Deployment existingDeployment;\n+ private final Deployment baseDeployment;\n- KeycloakDeployment(KubernetesClient client) {\n- this.client = client;\n+ public KeycloakDeployment(KubernetesClient client, Config config, Keycloak keycloakCR, Deployment existingDeployment) {\n+ super(client, keycloakCR);\n+ this.config = config;\n+ this.keycloakCR = keycloakCR;\n+\n+ if (existingDeployment != null) {\n+ Log.info(\"Existing Deployment provided by controller\");\n+ this.existingDeployment = existingDeployment;\n+ }\n+ else {\n+ Log.info(\"Trying to fetch existing Deployment from the API\");\n+ this.existingDeployment = fetchExistingDeployment();\n+ }\n+\n+ baseDeployment = createBaseDeployment();\n+ }\n+\n+ @Override\n+ protected HasMetadata getReconciledResource() {\n+ Deployment baseDeployment = new DeploymentBuilder(this.baseDeployment).build(); // clone not to change the base template\n+ Deployment reconciledDeployment;\n+ if (existingDeployment == null) {\n+ Log.info(\"No existing Deployment found, using the default\");\n+ reconciledDeployment = baseDeployment;\n+ }\n+ else {\n+ Log.info(\"Existing Deployment found, updating specs\");\n+ reconciledDeployment = existingDeployment;\n+ // don't override metadata, just specs\n+ reconciledDeployment.setSpec(baseDeployment.getSpec());\n}\n- private Deployment baseDeployment;\n+ return reconciledDeployment;\n+ }\n- public Deployment getKeycloakDeployment(Keycloak keycloak) {\n- // TODO this should be done through an informer to leverage caches\n- // WORKAROUND for: https://github.com/java-operator-sdk/java-operator-sdk/issues/781\n+ private Deployment fetchExistingDeployment() {\nreturn client\n.apps()\n.deployments()\n- .inNamespace(keycloak.getMetadata().getNamespace())\n- .list()\n- .getItems()\n- .stream()\n- .filter((d) -> d.getMetadata().getName().equals(org.keycloak.operator.Constants.NAME))\n- .findFirst()\n- .orElse(null);\n-// .withName(Constants.NAME)\n-// .get();\n- }\n-\n- public void createKeycloakDeployment(Keycloak keycloak) {\n- client\n- .apps()\n- .deployments()\n- .inNamespace(keycloak.getMetadata().getNamespace())\n- .create(newKeycloakDeployment(keycloak));\n+ .inNamespace(getNamespace())\n+ .withName(getName())\n+ .get();\n}\n- public Deployment newKeycloakDeployment(Keycloak keycloak) {\n- if (baseDeployment == null) {\n- URL url = this.getClass().getResource(\"/base-deployment.yaml\");\n- baseDeployment = client.apps().deployments().load(url).get();\n+ private Deployment createBaseDeployment() {\n+ URL url = this.getClass().getResource(\"/base-keycloak-deployment.yaml\");\n+ Deployment baseDeployment = client.apps().deployments().load(url).get();\n+\n+ baseDeployment.getMetadata().setName(getName());\n+ baseDeployment.getMetadata().setNamespace(getNamespace());\n+ baseDeployment.getSpec().getSelector().setMatchLabels(Constants.DEFAULT_LABELS);\n+ baseDeployment.getSpec().setReplicas(keycloakCR.getSpec().getInstances());\n+ baseDeployment.getSpec().getTemplate().getMetadata().setLabels(Constants.DEFAULT_LABELS);\n+\n+ Container container = baseDeployment.getSpec().getTemplate().getSpec().getContainers().get(0);\n+ container.setImage(Optional.ofNullable(keycloakCR.getSpec().getImage()).orElse(config.keycloak().image()));\n+\n+ var serverConfig = new HashMap<>(Constants.DEFAULT_DIST_CONFIG);\n+ if (keycloakCR.getSpec().getServerConfiguration() != null) {\n+ serverConfig.putAll(keycloakCR.getSpec().getServerConfiguration());\n+ }\n+\n+ container.setEnv(serverConfig.entrySet().stream()\n+ .map(e -> new EnvVarBuilder().withName(e.getKey()).withValue(e.getValue()).build())\n+ .collect(Collectors.toList()));\n+\n+// Set<String> configSecretsNames = new HashSet<>();\n+// List<EnvVar> configEnvVars = serverConfig.entrySet().stream()\n+// .map(e -> {\n+// EnvVarBuilder builder = new EnvVarBuilder().withName(e.getKey());\n+// Matcher matcher = CONFIG_SECRET_PATTERN.matcher(e.getValue());\n+// // check if given config var is actually a secret reference\n+// if (matcher.matches()) {\n+// builder.withValueFrom(\n+// new EnvVarSourceBuilder()\n+// .withNewSecretKeyRef(matcher.group(2), matcher.group(1), false)\n+// .build());\n+// configSecretsNames.add(matcher.group(1)); // for watching it later\n+// } else {\n+// builder.withValue(e.getValue());\n+// }\n+// builder.withValue(e.getValue());\n+// return builder.build();\n+// })\n+// .collect(Collectors.toList());\n+// container.setEnv(configEnvVars);\n+// this.configSecretsNames = Collections.unmodifiableSet(configSecretsNames);\n+// Log.infof(\"Found config secrets names: %s\", configSecretsNames);\n+\n+ return baseDeployment;\n}\n- var deployment = baseDeployment;\n+ public void updateStatus(KeycloakStatusBuilder status) {\n+ if (existingDeployment == null) {\n+ status.addNotReadyMessage(\"No existing Deployment found, waiting for creating a new one\");\n+ return;\n+ }\n- deployment\n- .getSpec()\n- .setReplicas(keycloak.getSpec().getInstances());\n+ var replicaFailure = existingDeployment.getStatus().getConditions().stream()\n+ .filter(d -> d.getType().equals(\"ReplicaFailure\")).findFirst();\n+ if (replicaFailure.isPresent()) {\n+ status.addNotReadyMessage(\"Deployment failures\");\n+ status.addErrorMessage(\"Deployment failure: \" + replicaFailure.get());\n+ return;\n+ }\n- return new DeploymentBuilder(deployment).build();\n+ if (existingDeployment.getStatus() == null\n+ || existingDeployment.getStatus().getReadyReplicas() == null\n+ || existingDeployment.getStatus().getReadyReplicas() < keycloakCR.getSpec().getInstances()) {\n+ status.addNotReadyMessage(\"Waiting for more replicas\");\n+ }\n}\n- public KeycloakStatus getNextStatus(KeycloakSpec desired, KeycloakStatus prev, Deployment current) {\n- var isReady = (current != null &&\n- current.getStatus() != null &&\n- current.getStatus().getReadyReplicas() != null &&\n- current.getStatus().getReadyReplicas() == desired.getInstances());\n+// public Set<String> getConfigSecretsNames() {\n+// return configSecretsNames;\n+// }\n- var newStatus = new KeycloakStatus();\n- if (isReady) {\n- newStatus.setState(UNKNOWN);\n- newStatus.setMessage(\"Keycloak status is unmanaged\");\n- } else {\n- newStatus.setState(READY);\n- newStatus.setMessage(\"Keycloak status is ready\");\n+ public String getName() {\n+ return keycloakCR.getMetadata().getName();\n}\n- return newStatus;\n+\n+ public String getNamespace() {\n+ return keycloakCR.getMetadata().getNamespace();\n}\n+ public void rollingRestart() {\n+ client.apps().deployments()\n+ .inNamespace(getNamespace())\n+ .withName(getName())\n+ .rolling().restart();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakSpec.java", "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakSpec.java", "diff": "*/\npackage org.keycloak.operator.v2alpha1.crds;\n+import io.fabric8.kubernetes.api.model.PodTemplate;\n+\n+import java.util.Map;\n+\npublic class KeycloakSpec {\nprivate int instances = 1;\n+ private String image;\n+ private Map<String, String> serverConfiguration;\npublic int getInstances() {\nreturn instances;\n@@ -27,4 +33,20 @@ public class KeycloakSpec {\npublic void setInstances(int instances) {\nthis.instances = instances;\n}\n+\n+ public String getImage() {\n+ return image;\n+ }\n+\n+ public void setImage(String image) {\n+ this.image = image;\n+ }\n+\n+ public Map<String, String> getServerConfiguration() {\n+ return serverConfiguration;\n+ }\n+\n+ public void setServerConfiguration(Map<String, String> serverConfiguration) {\n+ this.serverConfiguration = serverConfiguration;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakStatus.java", "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakStatus.java", "diff": "*/\npackage org.keycloak.operator.v2alpha1.crds;\n-public class KeycloakStatus {\n- public enum State {\n- READY,\n- ERROR,\n- UNKNOWN\n- }\n-\n- private State state = State.UNKNOWN;\n- private boolean error;\n- private String message;\n-\n- public State getState() {\n- return state;\n- }\n+import java.util.List;\n+import java.util.Objects;\n- public void setState(State state) {\n- this.state = state;\n- }\n-\n- public boolean isError() {\n- return error;\n- }\n+/**\n+ * @author Vaclav Muzikar <[email protected]>\n+ */\n+public class KeycloakStatus {\n+ private List<KeycloakStatusCondition> conditions;\n- public void setError(boolean error) {\n- this.error = error;\n+ public List<KeycloakStatusCondition> getConditions() {\n+ return conditions;\n}\n- public String getMessage() {\n- return message;\n+ public void setConditions(List<KeycloakStatusCondition> conditions) {\n+ this.conditions = conditions;\n}\n- public void setMessage(String message) {\n- this.message = message;\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (o == null || getClass() != o.getClass()) return false;\n+ KeycloakStatus status = (KeycloakStatus) o;\n+ return Objects.equals(getConditions(), status.getConditions());\n}\n- public KeycloakStatus clone() {\n- var status = new KeycloakStatus();\n- status.setMessage(this.message);\n- status.setState(this.state);\n- status.setError(this.error);\n- return status;\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(getConditions());\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakStatusBuilder.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.operator.v2alpha1.crds;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+/**\n+ * @author Vaclav Muzikar <[email protected]>\n+ */\n+public class KeycloakStatusBuilder {\n+ private final KeycloakStatusCondition readyCondition;\n+ private final KeycloakStatusCondition hasErrorsCondition;\n+\n+ private final List<String> notReadyMessages = new ArrayList<>();\n+ private final List<String> errorMessages = new ArrayList<>();\n+\n+ public KeycloakStatusBuilder() {\n+ readyCondition = new KeycloakStatusCondition();\n+ readyCondition.setType(KeycloakStatusCondition.READY);\n+ readyCondition.setStatus(true);\n+\n+ hasErrorsCondition = new KeycloakStatusCondition();\n+ hasErrorsCondition.setType(KeycloakStatusCondition.HAS_ERRORS);\n+ hasErrorsCondition.setStatus(false);\n+ }\n+\n+ public KeycloakStatusBuilder addNotReadyMessage(String message) {\n+ readyCondition.setStatus(false);\n+ notReadyMessages.add(message);\n+ return this;\n+ }\n+\n+ public KeycloakStatusBuilder addErrorMessage(String message) {\n+ hasErrorsCondition.setStatus(true);\n+ errorMessages.add(message);\n+ return this;\n+ }\n+\n+ public KeycloakStatus build() {\n+ readyCondition.setMessage(String.join(\"\\n\", notReadyMessages));\n+ hasErrorsCondition.setMessage(String.join(\"\\n\", errorMessages));\n+\n+ KeycloakStatus status = new KeycloakStatus();\n+ status.setConditions(List.of(readyCondition, hasErrorsCondition));\n+ return status;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakStatusCondition.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.operator.v2alpha1.crds;\n+\n+import java.io.Serializable;\n+import java.util.Objects;\n+\n+/**\n+ * @author Vaclav Muzikar <[email protected]>\n+ */\n+public class KeycloakStatusCondition {\n+ public static final String READY = \"Ready\";\n+ public static final String HAS_ERRORS = \"HasErrors\";\n+\n+ // string to avoid enums in CRDs\n+ private String type;\n+ private Boolean status;\n+ private String message;\n+\n+ public String getType() {\n+ return type;\n+ }\n+\n+ public void setType(String type) {\n+ this.type = type;\n+ }\n+\n+ public Boolean getStatus() {\n+ return status;\n+ }\n+\n+ public void setStatus(Boolean status) {\n+ this.status = status;\n+ }\n+\n+ public String getMessage() {\n+ return message;\n+ }\n+\n+ public void setMessage(String message) {\n+ this.message = message;\n+ }\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (o == null || getClass() != o.getClass()) return false;\n+ KeycloakStatusCondition that = (KeycloakStatusCondition) o;\n+ return getType() == that.getType() && Objects.equals(getStatus(), that.getStatus()) && Objects.equals(getMessage(), that.getMessage());\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(getType(), getStatus(), getMessage());\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/resources/application.properties", "new_path": "operator/src/main/resources/application.properties", "diff": "@@ -2,3 +2,6 @@ quarkus.operator-sdk.crd.apply=true\nquarkus.operator-sdk.generate-csv=true\nquarkus.container-image.builder=jib\nquarkus.operator-sdk.crd.validate=false\n+\n+# Operator config\n+operator.keycloak.image=quay.io/keycloak/keycloak-x:latest\n\\ No newline at end of file\n" }, { "change_type": "RENAME", "old_path": "operator/src/main/resources/base-deployment.yaml", "new_path": "operator/src/main/resources/base-keycloak-deployment.yaml", "diff": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n- labels:\n- app.kubernetes.io/managed-by: keycloak-operator\n- name: keycloak\n- namespace: default\n+ name: \"\"\nspec:\n- replicas: 1\nselector:\nmatchLabels:\n- app: keycloak\n+ app: \"\"\nstrategy:\nrollingUpdate:\nmaxSurge: 25%\n@@ -18,12 +14,11 @@ spec:\ntemplate:\nmetadata:\nlabels:\n- app: keycloak\n+ app: \"\"\nspec:\ncontainers:\n- args:\n- start-dev\n- image: quay.io/keycloak/keycloak-x:latest\nimagePullPolicy: Always\nname: keycloak\nports:\n@@ -31,10 +26,17 @@ spec:\nprotocol: TCP\n- containerPort: 8080\nprotocol: TCP\n+ livenessProbe:\n+ exec:\n+ command:\n+ - curl --head --fail --silent http://127.0.0.1:8080/health/live\n+ periodSeconds: 1\n+ readinessProbe:\n+ exec:\n+ command:\n+ - curl --head --fail --silent http://127.0.0.1:8080/health/ready\n+ periodSeconds: 1\n+ failureThreshold: 180\ndnsPolicy: ClusterFirst\n- initContainers:\n- - image: quay.io/keycloak/keycloak-init-container:latest\n- imagePullPolicy: Always\n- name: init-container\nrestartPolicy: Always\nterminationGracePeriodSeconds: 30\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/resources/example-keycloak.yml", "new_path": "operator/src/main/resources/example-keycloak.yml", "diff": "-apiVersion: keycloak.io/v2alpha1\n+apiVersion: keycloak.org/v2alpha1\nkind: Keycloak\nmetadata:\nname: example-kc\nspec:\ninstances: 1\n+ distConfig:\n+ KC_DB: postgres\n+ KC_DB_URL_HOST: postgres-db\n+# KC_DB_USERNAME: ${secret:keycloak-db-secret:username}\n+# KC_DB_PASSWORD: ${secret:keycloak-db-secret:password}\n+ KC_DB_USERNAME: postgres\n+ KC_DB_PASSWORD: testpassword\n+---\n+apiVersion: v1\n+kind: Secret\n+metadata:\n+ name: keycloak-db-secret\n+data:\n+ username: cG9zdGdyZXM= # postgres\n+ password: dGVzdHBhc3N3b3Jk # testpassword\n+type: Opaque\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/main/resources/example-postgres.yaml", "diff": "+# PostgreSQL StatefulSet\n+apiVersion: apps/v1\n+kind: StatefulSet\n+metadata:\n+ name: postgresql-db\n+spec:\n+ serviceName: postgresql-db-service\n+ selector:\n+ matchLabels:\n+ app: postgresql-db\n+ replicas: 1\n+ template:\n+ metadata:\n+ labels:\n+ app: postgresql-db\n+ spec:\n+ containers:\n+ - name: postgresql-db\n+ image: postgres:latest\n+ env:\n+ - name: POSTGRES_PASSWORD\n+ value: testpassword\n+ - name: PGDATA\n+ value: /data/pgdata\n+ - name: POSTGRES_DB\n+ value: keycloak\n+---\n+# PostgreSQL StatefulSet Service\n+apiVersion: v1\n+kind: Service\n+metadata:\n+ name: postgres-db\n+spec:\n+ selector:\n+ app: postgresql-db\n+ type: LoadBalancer\n+ ports:\n+ - port: 5432\n+ targetPort: 5432\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Baseline for Keycloak deployment in operator
339,618
26.01.2022 09:02:25
-3,600
af9d840ec1ef424ce333fc0b67968322a02a7c2d
Add section about recommended path exposures in reverse proxy Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/proxy.adoc", "new_path": "docs/guides/src/main/server/proxy.adoc", "diff": "@@ -35,4 +35,48 @@ Please consult the documentation of your reverse proxy on how to set these heade\nTake extra precautions to ensure that the X-Forwarded-For header is set by your reverse proxy. If it is not configured correctly, rogue clients can set this header themselves and trick Keycloak into thinking the client is connecting from a different IP address than it actually does. This may become really important if you are doing any black or white listing of IP addresses.\n+=== Exposed path recommendations\n+When using a reverse proxy, not all paths have to be exposed in order for Keycloak to work correctly. The recommendations on which paths to expose and which not to expose are as follows:\n+\n+|===\n+|Keycloak Path|Reverse Proxy Path|Exposed|Reason\n+\n+|/\n+|-\n+|No\n+|When exposing all paths, admin paths are exposed unnecessarily\n+\n+|/admin/\n+| -\n+|No\n+|Exposed admin paths lead to an unnecessary attack vector\n+\n+|/js/\n+| -\n+|No\n+|It's good practice to not use external js for the javascript client, but bake it into your public client instead\n+\n+|/welcome/\n+| -\n+|No\n+|No need to expose the welcome page after initial installation.\n+\n+|/realms/\n+|/realms/\n+|Yes\n+|Needed to work correctly (e.g. oidc endpoints)\n+\n+|/resources/\n+|/resources/\n+|Yes\n+|Needed to serve assets correctly. May be served from a CDN instead of the Keycloak path.\n+\n+|/robots.txt\n+|/robots.txt\n+|Yes\n+|Search engine rules\n+\n+|===\n+We assume you run Keycloak on the root path `/` on your reverse proxy/gateways public API. If not, prefix the path with your desired one.\n+\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add section about recommended path exposures in reverse proxy (#9752) Closes #9751
339,179
24.01.2022 10:26:11
-3,600
de161d02b92a99b16eb6274a9d55bae154ec7c3f
Store updated flag in the entity, not in the delegate Closes
[ { "change_type": "MODIFY", "old_path": "model/build-processor/src/main/java/org/keycloak/models/map/annotations/GenerateHotRodEntityImplementation.java", "new_path": "model/build-processor/src/main/java/org/keycloak/models/map/annotations/GenerateHotRodEntityImplementation.java", "diff": "@@ -26,5 +26,5 @@ import java.lang.annotation.Target;\n@Target(ElementType.TYPE)\npublic @interface GenerateHotRodEntityImplementation {\nString implementInterface();\n- String inherits() default \"org.keycloak.models.map.common.UpdatableEntity.Impl\";\n+ String inherits() default \"org.keycloak.models.map.storage.hotRod.common.UpdatableHotRodEntityDelegateImpl\";\n}\n" }, { "change_type": "MODIFY", "old_path": "model/build-processor/src/main/java/org/keycloak/models/map/processor/GenerateHotRodEntityImplementationsProcessor.java", "new_path": "model/build-processor/src/main/java/org/keycloak/models/map/processor/GenerateHotRodEntityImplementationsProcessor.java", "diff": "@@ -77,6 +77,8 @@ public class GenerateHotRodEntityImplementationsProcessor extends AbstractGenera\nif (interfaceClass == null || interfaceClass.isEmpty()) return;\nTypeElement parentClassElement = elements.getTypeElement(hotRodAnnotation.inherits());\nif (parentClassElement == null) return;\n+ boolean parentClassHasGeneric = !getGenericsDeclaration(parentClassElement.asType()).isEmpty();\n+\nTypeElement parentInterfaceElement = elements.getTypeElement(interfaceClass);\nif (parentInterfaceElement == null) return;\n@@ -119,9 +121,11 @@ public class GenerateHotRodEntityImplementationsProcessor extends AbstractGenera\npw.println(\"import java.util.stream.Collectors;\");\npw.println();\npw.println(\"// DO NOT CHANGE THIS CLASS, IT IS GENERATED AUTOMATICALLY BY \" + GenerateHotRodEntityImplementationsProcessor.class.getSimpleName());\n- pw.println(\"public class \" + hotRodSimpleClassName + \" extends \" + parentClassElement.getQualifiedName().toString() + \" implements \"\n+ pw.println(\"public class \" + hotRodSimpleClassName\n+ + \" extends \"\n+ + parentClassElement.getQualifiedName().toString() + (parentClassHasGeneric ? \"<\" + e.getQualifiedName().toString() + \">\" : \"\")\n+ + \" implements \"\n+ parentInterfaceElement.getQualifiedName().toString()\n- + \", \" + generalHotRodDelegate.getQualifiedName().toString() + \"<\" + e.getQualifiedName().toString() + \">\"\n+ \" {\");\npw.println();\npw.println(\" private final \" + className + \" \" + ENTITY_VARIABLE + \";\");\n@@ -325,7 +329,7 @@ public class GenerateHotRodEntityImplementationsProcessor extends AbstractGenera\npw.println(\" p0 = \" + deepClone(fieldType, \"p0\") + \";\");\n}\npw.println(\" \" + hotRodFieldType.toString() + \" migrated = \" + migrateToType(hotRodFieldType, firstParameterType, \"p0\") + \";\");\n- pw.println(\" updated |= ! Objects.equals(\" + hotRodEntityField(fieldName) + \", migrated);\");\n+ pw.println(\" \" + hotRodEntityField(\"updated\") + \" |= ! Objects.equals(\" + hotRodEntityField(fieldName) + \", migrated);\");\npw.println(\" \" + hotRodEntityField(fieldName) + \" = migrated;\");\npw.println(\" }\");\nreturn true;\n@@ -338,10 +342,10 @@ public class GenerateHotRodEntityImplementationsProcessor extends AbstractGenera\n}\npw.println(\" \" + collectionItemType.toString() + \" migrated = \" + migrateToType(collectionItemType, firstParameterType, \"p0\") + \";\");\nif (isSetType(typeElement)) {\n- pw.println(\" updated |= \" + hotRodEntityField(fieldName) + \".add(migrated);\");\n+ pw.println(\" \" + hotRodEntityField(\"updated\") + \" |= \" + hotRodEntityField(fieldName) + \".add(migrated);\");\n} else {\npw.println(\" \" + hotRodEntityField(fieldName) + \".add(migrated);\");\n- pw.println(\" updated = true;\");\n+ pw.println(\" \" + hotRodEntityField(\"updated\") + \" = true;\");\n}\npw.println(\" }\");\nreturn true;\n@@ -350,7 +354,7 @@ public class GenerateHotRodEntityImplementationsProcessor extends AbstractGenera\npw.println(\" @SuppressWarnings(\\\"unchecked\\\") @Override public \" + method.getReturnType() + \" \" + method.getSimpleName() + \"(\" + firstParameterType + \" p0) {\");\nif (isMapType(typeElement)) {\n// Maps are stored as sets\n- pw.println(\" this.updated |= \" + hotRodUtils.getQualifiedName().toString() + \".removeFromSetByMapKey(\"\n+ pw.println(\" \" + hotRodEntityField(\"updated\") + \" |= \" + hotRodUtils.getQualifiedName().toString() + \".removeFromSetByMapKey(\"\n+ hotRodEntityField(fieldName) + \", \"\n+ \"p0, \"\n+ keyGetterReference(collectionItemType) + \");\"\n@@ -358,7 +362,7 @@ public class GenerateHotRodEntityImplementationsProcessor extends AbstractGenera\n} else {\npw.println(\" if (\" + hotRodEntityField(fieldName) + \" == null) { return; }\");\npw.println(\" boolean removed = \" + hotRodEntityField(fieldName) + \".remove(p0);\");\n- pw.println(\" updated |= removed;\");\n+ pw.println(\" \" + hotRodEntityField(\"updated\") + \" |= removed;\");\n}\npw.println(\" }\");\nreturn true;\n@@ -371,12 +375,12 @@ public class GenerateHotRodEntityImplementationsProcessor extends AbstractGenera\nif (! isImmutableFinalType(secondParameterType)) {\npw.println(\" p1 = \" + deepClone(secondParameterType, \"p1\") + \";\");\n}\n- pw.println(\" this.updated |= \" + hotRodUtils.getQualifiedName().toString() + \".removeFromSetByMapKey(\"\n+ pw.println(\" \" + hotRodEntityField(\"updated\") + \" |= \" + hotRodUtils.getQualifiedName().toString() + \".removeFromSetByMapKey(\"\n+ hotRodEntityField(fieldName) + \", \"\n+ \"p0, \"\n+ keyGetterReference(collectionItemType) + \");\"\n);\n- pw.println(\" this.updated |= !valueUndefined && \" + hotRodEntityField(fieldName)\n+ pw.println(\" \" + hotRodEntityField(\"updated\") + \" |= !valueUndefined && \" + hotRodEntityField(fieldName)\n+ \".add(\" + migrateToType(collectionItemType, new TypeMirror[]{firstParameterType, secondParameterType}, new String[]{\"p0\", \"p1\"}) + \");\");\npw.println(\" }\");\nreturn true;\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/client/HotRodClientEntity.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/client/HotRodClientEntity.java", "diff": "@@ -22,10 +22,9 @@ import org.infinispan.protostream.annotations.ProtoField;\nimport org.keycloak.models.map.annotations.GenerateHotRodEntityImplementation;\nimport org.keycloak.models.map.storage.hotRod.common.AbstractHotRodEntity;\nimport org.keycloak.models.map.storage.hotRod.common.HotRodAttributeEntity;\n-import org.keycloak.models.map.storage.hotRod.common.HotRodEntityDelegate;\nimport org.keycloak.models.map.storage.hotRod.common.HotRodPair;\nimport org.keycloak.models.map.client.MapClientEntity;\n-import org.keycloak.models.map.common.UpdatableEntity;\n+import org.keycloak.models.map.storage.hotRod.common.UpdatableHotRodEntityDelegateImpl;\nimport java.util.Collection;\nimport java.util.LinkedList;\n@@ -40,7 +39,7 @@ import java.util.stream.Stream;\ninherits = \"org.keycloak.models.map.storage.hotRod.client.HotRodClientEntity.AbstractHotRodClientEntityDelegate\"\n)\n@ProtoDoc(\"@Indexed\")\n-public class HotRodClientEntity implements AbstractHotRodEntity {\n+public class HotRodClientEntity extends AbstractHotRodEntity {\n@ProtoField(number = 1, required = true)\npublic int entityVersion = 1;\n@@ -160,7 +159,7 @@ public class HotRodClientEntity implements AbstractHotRodEntity {\n@ProtoField(number = 36)\npublic Integer nodeReRegistrationTimeout;\n- public static abstract class AbstractHotRodClientEntityDelegate extends UpdatableEntity.Impl implements HotRodEntityDelegate<HotRodClientEntity>, MapClientEntity {\n+ public static abstract class AbstractHotRodClientEntityDelegate extends UpdatableHotRodEntityDelegateImpl<HotRodClientEntity> implements MapClientEntity {\n@Override\npublic String getId() {\n@@ -172,13 +171,13 @@ public class HotRodClientEntity implements AbstractHotRodEntity {\nHotRodClientEntity entity = getHotRodEntity();\nif (entity.id != null) throw new IllegalStateException(\"Id cannot be changed\");\nentity.id = id;\n- this.updated |= id != null;\n+ entity.updated |= id != null;\n}\n@Override\npublic void setClientId(String clientId) {\nHotRodClientEntity entity = getHotRodEntity();\n- this.updated |= ! Objects.equals(entity.clientId, clientId);\n+ entity.updated |= ! Objects.equals(entity.clientId, clientId);\nentity.clientId = clientId;\nentity.clientIdLowercase = clientId == null ? null : clientId.toLowerCase();\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/client/HotRodProtocolMapperEntity.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/client/HotRodProtocolMapperEntity.java", "diff": "@@ -26,7 +26,7 @@ import java.util.Objects;\nimport java.util.Set;\n@GenerateHotRodEntityImplementation(implementInterface = \"org.keycloak.models.map.client.MapProtocolMapperEntity\")\n-public class HotRodProtocolMapperEntity implements AbstractHotRodEntity {\n+public class HotRodProtocolMapperEntity extends AbstractHotRodEntity {\n@ProtoField(number = 1)\npublic String id;\n@ProtoField(number = 2)\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/AbstractHotRodEntity.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/AbstractHotRodEntity.java", "diff": "package org.keycloak.models.map.storage.hotRod.common;\n-public interface AbstractHotRodEntity {\n+import org.keycloak.models.map.common.UpdatableEntity;\n+\n+public abstract class AbstractHotRodEntity implements UpdatableEntity {\n+ public boolean updated;\n+\n+ @Override\n+ public boolean isUpdated() {\n+ return this.updated;\n+ }\n+\n+ @Override\n+ public void clearUpdatedFlag() {\n+ this.updated = false;\n+ }\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/UpdatableHotRodEntityDelegateImpl.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.models.map.storage.hotRod.common;\n+\n+import org.keycloak.models.map.common.UpdatableEntity;\n+\n+public abstract class UpdatableHotRodEntityDelegateImpl<E extends UpdatableEntity> implements HotRodEntityDelegate<E> {\n+\n+ @Override\n+ public boolean isUpdated() {\n+ return getHotRodEntity().isUpdated();\n+ }\n+\n+ @Override\n+ public void clearUpdatedFlag() {\n+ getHotRodEntity().clearUpdatedFlag();\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/group/HotRodGroupEntity.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/group/HotRodGroupEntity.java", "diff": "@@ -20,11 +20,10 @@ package org.keycloak.models.map.storage.hotRod.group;\nimport org.infinispan.protostream.annotations.ProtoDoc;\nimport org.infinispan.protostream.annotations.ProtoField;\nimport org.keycloak.models.map.annotations.GenerateHotRodEntityImplementation;\n-import org.keycloak.models.map.common.UpdatableEntity;\nimport org.keycloak.models.map.group.MapGroupEntity;\nimport org.keycloak.models.map.storage.hotRod.common.AbstractHotRodEntity;\nimport org.keycloak.models.map.storage.hotRod.common.HotRodAttributeEntityNonIndexed;\n-import org.keycloak.models.map.storage.hotRod.common.HotRodEntityDelegate;\n+import org.keycloak.models.map.storage.hotRod.common.UpdatableHotRodEntityDelegateImpl;\nimport java.util.Objects;\nimport java.util.Set;\n@@ -34,9 +33,9 @@ import java.util.Set;\ninherits = \"org.keycloak.models.map.storage.hotRod.group.HotRodGroupEntity.AbstractHotRodGroupEntityDelegate\"\n)\n@ProtoDoc(\"@Indexed\")\n-public class HotRodGroupEntity implements AbstractHotRodEntity {\n+public class HotRodGroupEntity extends AbstractHotRodEntity {\n- public static abstract class AbstractHotRodGroupEntityDelegate extends UpdatableEntity.Impl implements HotRodEntityDelegate<HotRodGroupEntity>, MapGroupEntity {\n+ public static abstract class AbstractHotRodGroupEntityDelegate extends UpdatableHotRodEntityDelegateImpl<HotRodGroupEntity> implements MapGroupEntity {\n@Override\npublic String getId() {\n@@ -48,13 +47,13 @@ public class HotRodGroupEntity implements AbstractHotRodEntity {\nHotRodGroupEntity entity = getHotRodEntity();\nif (entity.id != null) throw new IllegalStateException(\"Id cannot be changed\");\nentity.id = id;\n- this.updated |= id != null;\n+ entity.updated |= id != null;\n}\n@Override\npublic void setName(String name) {\nHotRodGroupEntity entity = getHotRodEntity();\n- updated |= ! Objects.equals(entity.name, name);\n+ entity.updated |= ! Objects.equals(entity.name, name);\nentity.name = name;\nentity.nameLowercase = name == null ? null : name.toLowerCase();\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Store updated flag in the entity, not in the delegate Closes #9774
339,410
24.01.2022 09:12:54
-3,600
9e257d4a0152e62569e7b6678e49c166e5d4524f
Added warning when storage contains multi-valued attributes and Keycloak model doesn't support them. Closes
[ { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/client/MapClientAdapter.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/client/MapClientAdapter.java", "diff": "*/\npackage org.keycloak.models.map.client;\n+import org.jboss.logging.Logger;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.ProtocolMapperModel;\n@@ -39,6 +40,7 @@ import java.util.stream.Stream;\n*/\npublic abstract class MapClientAdapter extends AbstractClientModel<MapClientEntity> implements ClientModel {\n+ private static final Logger LOG = Logger.getLogger(MapClientAdapter.class);\nprivate final MapProtocolMapperUtils pmUtils;\npublic MapClientAdapter(KeycloakSession session, RealmModel realm, MapClientEntity entity) {\n@@ -286,7 +288,15 @@ public abstract class MapClientAdapter extends AbstractClientModel<MapClientEnti\nfinal Map<String, List<String>> a = attributes == null ? Collections.emptyMap() : attributes;\nreturn a.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,\nentry -> {\n- if (entry.getValue().isEmpty()) return null;\n+ if (entry.getValue().isEmpty()) {\n+ return null;\n+ } else if (entry.getValue().size() > 1) {\n+ // This could be caused by an inconsistency in the storage, a programming error,\n+ // or a downgrade from a future version of Keycloak that already supports multi-valued attributes.\n+ // The caller will not see the other values, and when this entity is later updated, the additional values will be lost.\n+ LOG.warnf(\"Client '%s' realm '%s' has attribute '%s' with %d values, retrieving only the first\", getClientId(), getRealm().getName(), entry.getKey(),\n+ entry.getValue().size());\n+ }\nreturn entry.getValue().get(0);\n})\n);\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/clientscope/MapClientScopeAdapter.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/clientscope/MapClientScopeAdapter.java", "diff": "@@ -25,6 +25,8 @@ import java.util.Objects;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n+\n+import org.jboss.logging.Logger;\nimport org.keycloak.models.ClientScopeModel;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.ProtocolMapperModel;\n@@ -37,6 +39,7 @@ import org.keycloak.models.utils.RoleUtils;\npublic class MapClientScopeAdapter extends AbstractClientScopeModel<MapClientScopeEntity> implements ClientScopeModel {\n+ private static final Logger LOG = Logger.getLogger(MapClientScopeAdapter.class);\nprivate final MapProtocolMapperUtils pmUtils;\npublic MapClientScopeAdapter(KeycloakSession session, RealmModel realm, MapClientScopeEntity entity) {\n@@ -115,7 +118,15 @@ public class MapClientScopeAdapter extends AbstractClientScopeModel<MapClientSco\nfinal Map<String, List<String>> a = attributes == null ? Collections.emptyMap() : attributes;\nreturn a.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,\nentry -> {\n- if (entry.getValue().isEmpty()) return null;\n+ if (entry.getValue().isEmpty()) {\n+ return null;\n+ } else if (entry.getValue().size() > 1) {\n+ // This could be caused by an inconsistency in the storage, a programming error,\n+ // or a downgrade from a future version of Keycloak that already supports multi-valued attributes.\n+ // The caller will not see the other values, and when this entity is later updated, the additional values will be lost.\n+ LOG.warnf(\"ClientScope '%s' realm '%s' has attribute '%s' with %d values, retrieving only the first\", getName(), getRealm().getName(), entry.getKey(),\n+ entry.getValue().size());\n+ }\nreturn entry.getValue().get(0);\n})\n);\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/realm/MapRealmAdapter.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/realm/MapRealmAdapter.java", "diff": "@@ -24,6 +24,8 @@ import static java.util.Objects.nonNull;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n+\n+import org.jboss.logging.Logger;\nimport org.keycloak.Config;\nimport org.keycloak.common.enums.SslRequired;\nimport org.keycloak.component.ComponentFactory;\n@@ -64,6 +66,7 @@ import org.keycloak.models.utils.ComponentUtil;\npublic class MapRealmAdapter extends AbstractRealmModel<MapRealmEntity> implements RealmModel {\n+ private static final Logger LOG = Logger.getLogger(MapRealmAdapter.class);\nprivate static final String ACTION_TOKEN_GENERATED_BY_USER_LIFESPAN = \"actionTokenGeneratedByUserLifespan\";\nprivate static final String DEFAULT_SIGNATURE_ALGORITHM = \"defaultSignatureAlgorithm\";\nprivate static final String BRUTE_FORCE_PROTECTED = \"bruteForceProtected\";\n@@ -207,7 +210,15 @@ public class MapRealmAdapter extends AbstractRealmModel<MapRealmEntity> implemen\npublic Map<String, String> getAttributes() {\nreturn entity.getAttributes().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,\nentry -> {\n- if (entry.getValue().isEmpty()) return null;\n+ if (entry.getValue().isEmpty()) {\n+ return null;\n+ } else if (entry.getValue().size() > 1) {\n+ // This could be caused by an inconsistency in the storage, a programming error,\n+ // or a downgrade from a future version of Keycloak that already supports multi-valued attributes.\n+ // The caller will not see the other values, and when this entity is later updated, the additional values be will lost.\n+ LOG.warnf(\"Realm '%s' has attribute '%s' with %d values, retrieving only the first\", getId(), entry.getKey(),\n+ entry.getValue().size());\n+ }\nreturn entry.getValue().get(0);\n})\n);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Added warning when storage contains multi-valued attributes and Keycloak model doesn't support them. Closes #9714
339,618
13.01.2022 12:44:54
-3,600
80072b30cda7d634d087dae05489b0bb855ca636
Features guide Closes
[ { "change_type": "MODIFY", "old_path": "common/src/main/java/org/keycloak/common/Profile.java", "new_path": "common/src/main/java/org/keycloak/common/Profile.java", "diff": "@@ -48,37 +48,43 @@ public class Profile {\n}\npublic enum Feature {\n- AUTHORIZATION(Type.DEFAULT),\n- ACCOUNT2(Type.DEFAULT),\n- ACCOUNT_API(Type.DEFAULT),\n- ADMIN_FINE_GRAINED_AUTHZ(Type.PREVIEW),\n- ADMIN2(Type.EXPERIMENTAL),\n- DOCKER(Type.DISABLED_BY_DEFAULT),\n- IMPERSONATION(Type.DEFAULT),\n- OPENSHIFT_INTEGRATION(Type.PREVIEW),\n- SCRIPTS(Type.PREVIEW),\n- TOKEN_EXCHANGE(Type.PREVIEW),\n- UPLOAD_SCRIPTS(DEPRECATED),\n- WEB_AUTHN(Type.DEFAULT, Type.PREVIEW),\n- CLIENT_POLICIES(Type.DEFAULT),\n- CIBA(Type.DEFAULT),\n- MAP_STORAGE(Type.EXPERIMENTAL),\n- PAR(Type.DEFAULT),\n- DECLARATIVE_USER_PROFILE(Type.PREVIEW),\n- DYNAMIC_SCOPES(Type.EXPERIMENTAL);\n-\n+ AUTHORIZATION(\"Authorization Service\", Type.DEFAULT),\n+ ACCOUNT2(\"New Account Management Console\", Type.DEFAULT),\n+ ACCOUNT_API(\"Account Management REST API\", Type.DEFAULT),\n+ ADMIN_FINE_GRAINED_AUTHZ(\"Fine-Grained Admin Permissions\", Type.PREVIEW),\n+ ADMIN2(\"New Admin Console\", Type.EXPERIMENTAL),\n+ DOCKER(\"Docker Registry protocol\", Type.DISABLED_BY_DEFAULT),\n+ IMPERSONATION(\"Ability for admins to impersonate users\", Type.DEFAULT),\n+ OPENSHIFT_INTEGRATION(\"Extension to enable securing OpenShift\", Type.PREVIEW),\n+ SCRIPTS(\"Write custom authenticators using JavaScript\", Type.PREVIEW),\n+ TOKEN_EXCHANGE(\"Token Exchange Service\", Type.PREVIEW),\n+ UPLOAD_SCRIPTS(\"Ability to upload custom JavaScript through Admin REST API\", DEPRECATED),\n+ WEB_AUTHN(\"W3C Web Authentication (WebAuthn)\", Type.DEFAULT, Type.PREVIEW),\n+ CLIENT_POLICIES(\"Client configuration policies\", Type.DEFAULT),\n+ CIBA(\"OpenID Connect Client Initiated Backchannel Authentication (CIBA)\", Type.DEFAULT),\n+ MAP_STORAGE(\"New store\", Type.EXPERIMENTAL),\n+ PAR(\"OAuth 2.0 Pushed Authorization Requests (PAR)\", Type.DEFAULT),\n+ DECLARATIVE_USER_PROFILE(\"Configure user profiles using a declarative style\", Type.PREVIEW),\n+ DYNAMIC_SCOPES(\"Dynamic OAuth 2.0 scopes\", Type.EXPERIMENTAL);\n+\n+ private String label;\nprivate final Type typeProject;\nprivate final Type typeProduct;\n- Feature(Type type) {\n- this(type, type);\n+ Feature(String label, Type type) {\n+ this(label, type, type);\n}\n- Feature(Type typeProject, Type typeProduct) {\n+ Feature(String label, Type typeProject, Type typeProduct) {\n+ this.label = label;\nthis.typeProject = typeProject;\nthis.typeProduct = typeProduct;\n}\n+ public String getLabel() {\n+ return label;\n+ }\n+\npublic Type getTypeProject() {\nreturn typeProject;\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/guides/src/main/server/features.adoc", "diff": "+<#import \"/templates/guide.adoc\" as tmpl>\n+<#import \"/templates/kc.adoc\" as kc>\n+<#import \"/templates/options.adoc\" as opts>\n+\n+<@tmpl.guide\n+title=\"Enabling and disabling features\"\n+summary=\"Understand how to configure Keycloak to use optional features\">\n+\n+Keycloak has packed some functionality in features, some of them not enabled by default. These features include features that are in tech preview or deprecated features. In addition there are some features that are enabled by default, but can be disabled if you don't need them for your specific usage scenario.\n+\n+== Enabling features\n+\n+Some supported features, and all preview features, are not enabled by default. To enable a feature use:\n+\n+<@kc.build parameters=\"--features=<name>[,<name>]\"/>\n+\n+For example to enable `docker` and `token-exchange` use:\n+\n+<@kc.build parameters=\"--features=docker,token-exchange\"/>\n+\n+All preview features can be enabled with the special name `preview`:\n+\n+<@kc.build parameters=\"--features=preview\"/>\n+\n+== Disabling features\n+\n+To disable a feature that is enabled by default use:\n+\n+<@kc.build parameters=\"--features-disabled=<name>[,<name>]\"/>\n+\n+For example to disable `impersonation` use:\n+\n+<@kc.build parameters=\"--features-disabled=impersonation\"/>\n+\n+It is also possible to disable all default features with:\n+\n+<@kc.build parameters=\"--features-disabled=default\"/>\n+\n+This can be used in combination with `features` to explicitly set what features should be available. If a feature is\n+added both to the `features-disabled` list and the `features` list it will be enabled.\n+\n+== Supported features\n+\n+The following list contains supported features that are enabled by default, and can be disabled if not needed.\n+\n+<@showFeatures ctx.features.supported/>\n+\n+=== Disabled by default\n+\n+The following list contains supported features that are not enabled by default, and can be enabled if needed.\n+\n+<@showFeatures ctx.features.supportedDisabledByDefault/>\n+\n+== Preview features\n+\n+Preview features are not enabled by default, and are not recommended for use in production. These features may change, or\n+even be removed, in a future release.\n+\n+<@showFeatures ctx.features.preview/>\n+\n+== Deprecated features\n+\n+The following list contains deprecated features that will be removed in a future release. These features are not enabled by default.\n+\n+<@showFeatures ctx.features.deprecated/>\n+\n+</@tmpl.guide>\n+\n+<#macro showFeatures features>\n+[cols=\"1,3\",role=\"features\"]\n+|===\n+<#list features as feature>\n+\n+|[.features-name]#${feature.name}#\n+|[.features-description]#${feature.description}#\n+</#list>\n+|===\n+</#macro>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "docs/maven-plugin/pom.xml", "new_path": "docs/maven-plugin/pom.xml", "diff": "</exclusion>\n</exclusions>\n</dependency>\n+ <dependency>\n+ <groupId>org.keycloak</groupId>\n+ <artifactId>keycloak-common</artifactId>\n+ <exclusions>\n+ <exclusion>\n+ <groupId>*</groupId>\n+ <artifactId>*</artifactId>\n+ </exclusion>\n+ </exclusions>\n+ </dependency>\n<dependency>\n<groupId>io.quarkus</groupId>\n<artifactId>quarkus-core</artifactId>\n" }, { "change_type": "MODIFY", "old_path": "docs/maven-plugin/src/main/java/org/keycloak/guides/maven/Context.java", "new_path": "docs/maven-plugin/src/main/java/org/keycloak/guides/maven/Context.java", "diff": "@@ -11,11 +11,13 @@ public class Context {\nprivate File srcDir;\nprivate Options options;\n+ private Features features;\nprivate List<Guide> guides;\npublic Context(File srcDir) throws IOException {\nthis.srcDir = srcDir;\nthis.options = new Options();\n+ this.features = new Features();\nthis.guides = new LinkedList<>();\n@@ -34,7 +36,12 @@ public class Context {\nreturn options;\n}\n+ public Features getFeatures() {\n+ return features;\n+ }\n+\npublic List<Guide> getGuides() {\nreturn guides;\n}\n+\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/maven-plugin/src/main/java/org/keycloak/guides/maven/Features.java", "diff": "+package org.keycloak.guides.maven;\n+\n+import org.keycloak.common.Profile;\n+\n+import java.util.Arrays;\n+import java.util.Comparator;\n+import java.util.List;\n+import java.util.stream.Collectors;\n+\n+public class Features {\n+\n+ private List<Feature> features;\n+\n+ public Features() {\n+ this.features = Arrays.stream(Profile.Feature.values())\n+ .filter(f -> !f.getTypeProject().equals(Profile.Type.EXPERIMENTAL))\n+ .map(f -> new Feature(f))\n+ .sorted(Comparator.comparing(Feature::getName))\n+ .collect(Collectors.toList());\n+ }\n+\n+ public List<Feature> getSupported() {\n+ return features.stream().filter(f -> f.getType().equals(Profile.Type.DEFAULT)).collect(Collectors.toList());\n+ }\n+\n+ public List<Feature> getSupportedDisabledByDefault() {\n+ return features.stream().filter(f -> f.getType().equals(Profile.Type.DISABLED_BY_DEFAULT)).collect(Collectors.toList());\n+ }\n+\n+ public List<Feature> getDeprecated() {\n+ return features.stream().filter(f -> f.getType().equals(Profile.Type.DEPRECATED)).collect(Collectors.toList());\n+ }\n+\n+ public List<Feature> getPreview() {\n+ return features.stream().filter(f -> f.getType().equals(Profile.Type.PREVIEW)).collect(Collectors.toList());\n+ }\n+\n+ public class Feature {\n+\n+ private Profile.Feature profileFeature;\n+\n+ public Feature(Profile.Feature profileFeature) {\n+ this.profileFeature = profileFeature;\n+ }\n+\n+ public String getName() {\n+ return profileFeature.name().toLowerCase().replaceAll(\"_\", \"-\");\n+ }\n+\n+ public String getDescription() {\n+ return profileFeature.getLabel();\n+ }\n+\n+ private Profile.Type getType() {\n+ return profileFeature.getTypeProject();\n+ }\n+\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Features guide Co-authored-by: stianst <[email protected]> Closes #9461
339,433
22.07.2021 06:09:28
25,200
9621d513b59b9425ebd8e7ad0a775e602c9060ac
Improve user search query
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java", "diff": "@@ -55,6 +55,7 @@ import javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Expression;\n+import javax.persistence.criteria.From;\nimport javax.persistence.criteria.Join;\nimport javax.persistence.criteria.JoinType;\nimport javax.persistence.criteria.Predicate;\n@@ -607,12 +608,20 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor\n@Override\npublic int getUsersCount(RealmModel realm, String search) {\n- TypedQuery<Long> query = em.createNamedQuery(\"searchForUserCount\", Long.class);\n- query.setParameter(\"realmId\", realm.getId());\n- query.setParameter(\"search\", \"%\" + search.toLowerCase() + \"%\");\n- Long count = query.getSingleResult();\n+ CriteriaBuilder builder = em.getCriteriaBuilder();\n+ CriteriaQuery<Long> queryBuilder = builder.createQuery(Long.class);\n+ Root<UserEntity> root = queryBuilder.from(UserEntity.class);\n- return count.intValue();\n+ queryBuilder.select(builder.count(root));\n+\n+ List<Predicate> predicates = new ArrayList<>();\n+\n+ predicates.add(builder.equal(root.get(\"realmId\"), realm.getId()));\n+ predicates.add(builder.or(getSearchOptionPredicateArray(search, builder, root)));\n+\n+ queryBuilder.where(predicates.toArray(new Predicate[0]));\n+\n+ return em.createQuery(queryBuilder).getSingleResult().intValue();\n}\n@Override\n@@ -621,13 +630,23 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor\nreturn 0;\n}\n- TypedQuery<Long> query = em.createNamedQuery(\"searchForUserCountInGroups\", Long.class);\n- query.setParameter(\"realmId\", realm.getId());\n- query.setParameter(\"search\", \"%\" + search.toLowerCase() + \"%\");\n- query.setParameter(\"groupIds\", groupIds);\n- Long count = query.getSingleResult();\n+ CriteriaBuilder builder = em.getCriteriaBuilder();\n+ CriteriaQuery<Long> queryBuilder = builder.createQuery(Long.class);\n- return count.intValue();\n+ Root<UserGroupMembershipEntity> groupMembership = queryBuilder.from(UserGroupMembershipEntity.class);\n+ Join<UserGroupMembershipEntity, UserEntity> userJoin = groupMembership.join(\"user\");\n+\n+ queryBuilder.select(builder.count(userJoin));\n+\n+ List<Predicate> predicates = new ArrayList<>();\n+\n+ predicates.add(builder.equal(userJoin.get(\"realmId\"), realm.getId()));\n+ predicates.add(builder.or(getSearchOptionPredicateArray(search, builder, userJoin)));\n+ predicates.add(groupMembership.get(\"groupId\").in(groupIds));\n+\n+ queryBuilder.where(predicates.toArray(new Predicate[0]));\n+\n+ return em.createQuery(queryBuilder).getSingleResult().intValue();\n}\n@Override\n@@ -789,21 +808,10 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor\nswitch (key) {\ncase UserModel.SEARCH:\n- List<Predicate> orPredicates = new ArrayList<>();\n-\n- orPredicates\n- .add(builder.like(builder.lower(root.get(USERNAME)), \"%\" + value.toLowerCase() + \"%\"));\n- orPredicates.add(builder.like(builder.lower(root.get(EMAIL)), \"%\" + value.toLowerCase() + \"%\"));\n- orPredicates.add(builder.like(\n- builder.lower(builder.concat(builder.concat(\n- builder.coalesce(root.get(FIRST_NAME), builder.literal(\"\")), \" \"),\n- builder.coalesce(root.get(LAST_NAME), builder.literal(\"\")))),\n- \"%\" + value.toLowerCase() + \"%\"));\n-\n- predicates.add(builder.or(orPredicates.toArray(new Predicate[0])));\n-\n+ for (String stringToSearch : value.trim().split(\"\\\\s+\")) {\n+ predicates.add(builder.or(getSearchOptionPredicateArray(stringToSearch, builder, root)));\n+ }\nbreak;\n-\ncase USERNAME:\ncase FIRST_NAME:\ncase LAST_NAME:\n@@ -1033,6 +1041,40 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor\n}\n}\n+ private Predicate[] getSearchOptionPredicateArray(String value, CriteriaBuilder builder, From<?, UserEntity> from) {\n+ value = value.toLowerCase();\n+\n+ List<Predicate> orPredicates = new ArrayList<>();\n+\n+ if (value.length() >= 2 && value.charAt(0) == '\"' && value.charAt(value.length() - 1) == '\"') {\n+ // exact search\n+ value = value.substring(1, value.length() - 1);\n+\n+ orPredicates.add(builder.equal(builder.lower(from.get(USERNAME)), value));\n+ orPredicates.add(builder.equal(builder.lower(from.get(EMAIL)), value));\n+ orPredicates.add(builder.equal(builder.lower(from.get(FIRST_NAME)), value));\n+ orPredicates.add(builder.equal(builder.lower(from.get(LAST_NAME)), value));\n+ } else {\n+ if (value.length() >= 2 && value.charAt(0) == '*' && value.charAt(value.length() - 1) == '*') {\n+ // infix search\n+ value = \"%\" + value.substring(1, value.length() - 1) + \"%\";\n+ } else {\n+ // default to prefix search\n+ if (value.length() > 0 && value.charAt(value.length() - 1) == '*') {\n+ value = value.substring(0, value.length() - 1);\n+ }\n+ value += \"%\";\n+ }\n+\n+ orPredicates.add(builder.like(builder.lower(from.get(USERNAME)), value));\n+ orPredicates.add(builder.like(builder.lower(from.get(EMAIL)), value));\n+ orPredicates.add(builder.like(builder.lower(from.get(FIRST_NAME)), value));\n+ orPredicates.add(builder.like(builder.lower(from.get(LAST_NAME)), value));\n+ }\n+\n+ return orPredicates.toArray(new Predicate[0]);\n+ }\n+\nprivate UserEntity userInEntityManagerContext(String id) {\nUserEntity user = em.getReference(UserEntity.class, id);\nboolean isLoaded = em.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded(user);\n" }, { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserEntity.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserEntity.java", "diff": "@@ -44,8 +44,6 @@ import java.util.LinkedList;\n@NamedQueries({\n@NamedQuery(name=\"getAllUsersByRealm\", query=\"select u from UserEntity u where u.realmId = :realmId order by u.username\"),\n@NamedQuery(name=\"getAllUsersByRealmExcludeServiceAccount\", query=\"select u from UserEntity u where u.realmId = :realmId and (u.serviceAccountClientLink is null) order by u.username\"),\n- @NamedQuery(name=\"searchForUserCount\", query=\"select count(u) from UserEntity u where u.realmId = :realmId and (u.serviceAccountClientLink is null) and \" +\n- \"( lower(u.username) like :search or lower(concat(coalesce(u.firstName, ''), ' ', coalesce(u.lastName, ''))) like :search or u.email like :search )\"),\n@NamedQuery(name=\"getRealmUserByUsername\", query=\"select u from UserEntity u where u.username = :username and u.realmId = :realmId\"),\n@NamedQuery(name=\"getRealmUserByEmail\", query=\"select u from UserEntity u where u.email = :email and u.realmId = :realmId\"),\n@NamedQuery(name=\"getRealmUserByLastName\", query=\"select u from UserEntity u where u.lastName = :lastName and u.realmId = :realmId\"),\n" }, { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserGroupMembershipEntity.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserGroupMembershipEntity.java", "diff": "@@ -41,8 +41,6 @@ import java.io.Serializable;\n@NamedQuery(name=\"deleteUserGroupMembershipsByRealmAndLink\", query=\"delete from UserGroupMembershipEntity mapping where mapping.user IN (select u from UserEntity u where u.realmId=:realmId and u.federationLink=:link)\"),\n@NamedQuery(name=\"deleteUserGroupMembershipsByGroup\", query=\"delete from UserGroupMembershipEntity m where m.groupId = :groupId\"),\n@NamedQuery(name=\"deleteUserGroupMembershipsByUser\", query=\"delete from UserGroupMembershipEntity m where m.user = :user\"),\n- @NamedQuery(name=\"searchForUserCountInGroups\", query=\"select count(m.user) from UserGroupMembershipEntity m where m.user.realmId = :realmId and (m.user.serviceAccountClientLink is null) and \" +\n- \"( lower(m.user.username) like :search or lower(concat(m.user.firstName, ' ', m.user.lastName)) like :search or m.user.email like :search ) and m.groupId in :groupIds\"),\n@NamedQuery(name=\"userCountInGroups\", query=\"select count(m.user) from UserGroupMembershipEntity m where m.user.realmId = :realmId and m.groupId in :groupIds\")\n})\n@Table(name=\"USER_GROUP_MEMBERSHIP\")\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/storage/chm/CriteriaOperator.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/storage/chm/CriteriaOperator.java", "diff": "@@ -44,6 +44,7 @@ class CriteriaOperator {\nprivate static final Logger LOG = Logger.getLogger(CriteriaOperator.class.getSimpleName());\nprivate static final Predicate<Object> ALWAYS_FALSE = o -> false;\n+ private static final Predicate<Object> ALWAYS_TRUE = o -> true;\nstatic {\nOPERATORS.put(Operator.EQ, CriteriaOperator::eq);\n@@ -190,6 +191,11 @@ class CriteriaOperator {\nObject value0 = getFirstArrayElement(value);\nif (value0 instanceof String) {\nString sValue = (String) value0;\n+\n+ if(Pattern.matches(\"^%+$\", sValue)) {\n+ return ALWAYS_TRUE;\n+ }\n+\nboolean anyBeginning = sValue.startsWith(\"%\");\nboolean anyEnd = sValue.endsWith(\"%\");\n@@ -210,6 +216,11 @@ class CriteriaOperator {\nObject value0 = getFirstArrayElement(value);\nif (value0 instanceof String) {\nString sValue = (String) value0;\n+\n+ if(Pattern.matches(\"^%+$\", sValue)) {\n+ return ALWAYS_TRUE;\n+ }\n+\nboolean anyBeginning = sValue.startsWith(\"%\");\nboolean anyEnd = sValue.endsWith(\"%\");\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java", "diff": "@@ -47,6 +47,7 @@ import org.keycloak.models.map.storage.ModelCriteriaBuilder.Operator;\nimport org.keycloak.models.map.storage.criteria.DefaultModelCriteria;\nimport org.keycloak.models.utils.KeycloakModelUtils;\nimport org.keycloak.storage.StorageId;\n+import org.keycloak.storage.UserStorageManager;\nimport org.keycloak.storage.UserStorageProvider;\nimport org.keycloak.storage.client.ClientStorageProvider;\n@@ -613,20 +614,10 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor\nswitch (key) {\ncase UserModel.SEARCH:\n- for (String stringToSearch : value.trim().split(\"\\\\s+\")) {\n- if (value.isEmpty()) {\n- continue;\n- }\n- final String s = exactSearch ? stringToSearch : (\"%\" + stringToSearch + \"%\");\n- mcb = mcb.or(\n- mcb.compare(SearchableFields.USERNAME, Operator.ILIKE, s),\n- mcb.compare(SearchableFields.EMAIL, Operator.ILIKE, s),\n- mcb.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, s),\n- mcb.compare(SearchableFields.LAST_NAME, Operator.ILIKE, s)\n- );\n+ for (String stringToSearch : value.split(\"\\\\s+\")) {\n+ mcb = addSearchToModelCriteria(stringToSearch, mcb);\n}\nbreak;\n-\ncase USERNAME:\nmcb = mcb.compare(SearchableFields.USERNAME, Operator.ILIKE, searchedString);\nbreak;\n@@ -656,7 +647,8 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor\nbreak;\n}\ncase UserModel.IDP_USER_ID: {\n- mcb = mcb.compare(SearchableFields.IDP_AND_USER, Operator.EQ, attributes.get(UserModel.IDP_ALIAS), value);\n+ mcb = mcb.compare(SearchableFields.IDP_AND_USER, Operator.EQ, attributes.get(UserModel.IDP_ALIAS),\n+ value);\nbreak;\n}\ncase UserModel.EXACT:\n@@ -678,7 +670,8 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor\nreturn Stream.empty();\n}\n- final ResourceStore resourceStore = session.getProvider(AuthorizationProvider.class).getStoreFactory().getResourceStore();\n+ final ResourceStore resourceStore =\n+ session.getProvider(AuthorizationProvider.class).getStoreFactory().getResourceStore();\nHashSet<String> authorizedGroups = new HashSet<>(userGroups);\nauthorizedGroups.removeIf(id -> {\n@@ -832,4 +825,30 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor\npublic void close() {\n}\n+\n+ private DefaultModelCriteria<UserModel> addSearchToModelCriteria(String value,\n+ DefaultModelCriteria<UserModel> mcb) {\n+\n+ if (value.length() >= 2 && value.charAt(0) == '\"' && value.charAt(value.length() - 1) == '\"') {\n+ // exact search\n+ value = value.substring(1, value.length() - 1);\n+ } else {\n+ if (value.length() >= 2 && value.charAt(0) == '*' && value.charAt(value.length() - 1) == '*') {\n+ // infix search\n+ value = \"%\" + value.substring(1, value.length() - 1) + \"%\";\n+ } else {\n+ // default to prefix search\n+ if (value.length() > 0 && value.charAt(value.length() - 1) == '*') {\n+ value = value.substring(0, value.length() - 1);\n+ }\n+ value += \"%\";\n+ }\n+ }\n+\n+ return mcb.or(\n+ mcb.compare(SearchableFields.USERNAME, Operator.ILIKE, value),\n+ mcb.compare(SearchableFields.EMAIL, Operator.ILIKE, value),\n+ mcb.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, value),\n+ mcb.compare(SearchableFields.LAST_NAME, Operator.ILIKE, value));\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserTest.java", "diff": "@@ -40,7 +40,6 @@ import org.keycloak.common.util.ObjectUtil;\nimport org.keycloak.credential.CredentialModel;\nimport org.keycloak.events.admin.OperationType;\nimport org.keycloak.events.admin.ResourceType;\n-import org.keycloak.jose.jws.JWSInput;\nimport org.keycloak.models.Constants;\nimport org.keycloak.models.LDAPConstants;\nimport org.keycloak.models.PasswordPolicy;\n@@ -93,7 +92,6 @@ import javax.mail.internet.MimeMessage;\nimport javax.ws.rs.BadRequestException;\nimport javax.ws.rs.ClientErrorException;\nimport javax.ws.rs.NotFoundException;\n-import javax.ws.rs.WebApplicationException;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.UriBuilder;\nimport java.io.IOException;\n@@ -723,7 +721,7 @@ public class UserTest extends AbstractAdminTest {\ncreateUser(user);\n- List<UserRepresentation> users = realm.users().search(\"wit\", null, null);\n+ List<UserRepresentation> users = realm.users().search(\"*wit*\", null, null);\nassertEquals(1, users.size());\n}\n@@ -925,25 +923,131 @@ public class UserTest extends AbstractAdminTest {\n}\n@Test\n- public void search() {\n- createUsers();\n+ public void infixSearch() {\n+ List<String> userIds = createUsers();\n- List<UserRepresentation> users = realm.users().search(\"username1\", null, null);\n- assertEquals(1, users.size());\n+ // Username search\n+ List<UserRepresentation> users = realm.users().search(\"*1*\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ users = realm.users().search(\"*y*\", null, null);\n+ assertThat(users.size(), is(0));\n+\n+ users = realm.users().search(\"*name*\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ users = realm.users().search(\"**\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ // First/Last name search\n+ users = realm.users().search(\"*first1*\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ users = realm.users().search(\"*last*\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ // Email search\n+ users = realm.users().search(\"*@localhost*\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ users = realm.users().search(\"*1@local*\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+ }\n+\n+ @Test\n+ public void prefixSearch() {\n+ List<String> userIds = createUsers();\n+\n+ // Username search\n+ List<UserRepresentation> users = realm.users().search(\"user\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ users = realm.users().search(\"user*\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ users = realm.users().search(\"name\", null, null);\n+ assertThat(users, hasSize(0));\n+\n+ users = realm.users().search(\"name*\", null, null);\n+ assertThat(users, hasSize(0));\n+\n+ users = realm.users().search(\"username1\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ users = realm.users().search(\"username1*\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ users = realm.users().search(null, null, null);\n+ assertThat(users, hasSize(9));\n+\n+ users = realm.users().search(\"\", null, null);\n+ assertThat(users, hasSize(9));\n+ users = realm.users().search(\"*\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ // First/Last name search\nusers = realm.users().search(\"first1\", null, null);\n- assertEquals(1, users.size());\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ users = realm.users().search(\"first1*\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\nusers = realm.users().search(\"last\", null, null);\n- assertEquals(9, users.size());\n+ assertThat(users, hasSize(9));\n+\n+ users = realm.users().search(\"last*\", null, null);\n+ assertThat(users, hasSize(9));\n+\n+ // Email search\n+ users = realm.users().search(\"user1@local\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ users = realm.users().search(\"user1@local*\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n}\n@Test\n- public void count() {\n+ public void circumfixSearchNotSupported() {\ncreateUsers();\n- Integer count = realm.users().count();\n- assertEquals(9, count.intValue());\n+ List<UserRepresentation> users = realm.users().search(\"u*name\", null, null);\n+ assertThat(users, hasSize(0));\n+ }\n+\n+ @Test\n+ public void exactSearch() {\n+ List<String> userIds = createUsers();\n+\n+ // Username search\n+ List<UserRepresentation> users = realm.users().search(\"\\\"username1\\\"\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ users = realm.users().search(\"\\\"user\\\"\", null, null);\n+ assertThat(users, hasSize(0));\n+\n+ users = realm.users().search(\"\\\"\\\"\", null, null);\n+ assertThat(users, hasSize(0));\n+\n+ // First/Last name search\n+ users = realm.users().search(\"\\\"first1\\\"\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n+\n+ // Email search\n+ users = realm.users().search(\"\\\"user1@localhost\\\"\", null, null);\n+ assertThat(users, hasSize(1));\n+ assertThat(userIds.get(0), equalTo(users.get(0).getId()));\n}\n@Test\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UsersTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UsersTest.java", "diff": "package org.keycloak.testsuite.admin;\nimport org.junit.Before;\n-import org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.keycloak.admin.client.Keycloak;\nimport org.keycloak.admin.client.resource.AuthorizationResource;\n@@ -49,7 +48,7 @@ import java.util.Optional;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.Matchers.empty;\nimport static org.hamcrest.Matchers.not;\n-import static org.junit.Assert.assertThat;\n+import static org.hamcrest.MatcherAssert.assertThat;\npublic class UsersTest extends AbstractAdminTest {\n@@ -111,25 +110,81 @@ public class UsersTest extends AbstractAdminTest {\n@Test\npublic void countUsersBySearchWithViewPermission() {\n- createUser(realmId, \"user1\", \"password\", \"user1FirstName\", \"user1LastName\", \"[email protected]\");\n- createUser(realmId, \"user2\", \"password\", \"user2FirstName\", \"user2LastName\", \"[email protected]\");\n- //search all\n- assertThat(realm.users().count(\"user\"), is(2));\n- //search first name\n- assertThat(realm.users().count(\"FirstName\"), is(2));\n- assertThat(realm.users().count(\"user2FirstName\"), is(1));\n- //search last name\n- assertThat(realm.users().count(\"LastName\"), is(2));\n- assertThat(realm.users().count(\"user2LastName\"), is(1));\n- //search in email\n- assertThat(realm.users().count(\"@example.com\"), is(2));\n- assertThat(realm.users().count(\"[email protected]\"), is(1));\n- //search for something not existing\n- assertThat(realm.users().count(\"notExisting\"), is(0));\n- //search for empty string\n- assertThat(realm.users().count(\"\"), is(2));\n- //search not specified (defaults to simply /count)\n- assertThat(realm.users().count(null), is(2));\n+ createUser(realmId, \"user1\", \"password\", \"user1FirstName\", \"user1LastName\", \"[email protected]\", rep -> rep.setEmailVerified(true));\n+ createUser(realmId, \"user2\", \"password\", \"user2FirstName\", \"user2LastName\", \"[email protected]\", rep -> rep.setEmailVerified(false));\n+ createUser(realmId, \"user3\", \"password\", \"user3FirstName\", \"user3LastName\", \"[email protected]\", rep -> rep.setEmailVerified(true));\n+\n+ // Prefix search count\n+ Integer count = realm.users().count(\"user\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"user*\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"er\");\n+ assertThat(count, is(0));\n+\n+ count = realm.users().count(\"\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"*\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"user2FirstName\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(\"user2First\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(\"user2First*\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(\"user1@example\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(\"user1@example*\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(null);\n+ assertThat(count, is(3));\n+\n+ // Infix search count\n+ count = realm.users().count(\"*user*\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"**\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"*foobar*\");\n+ assertThat(count, is(0));\n+\n+ count = realm.users().count(\"*LastName*\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"*FirstName*\");\n+ assertThat(count, is(3));\n+\n+ count = realm.users().count(\"*@example.com*\");\n+ assertThat(count, is(3));\n+\n+ // Exact search count\n+ count = realm.users().count(\"\\\"user1\\\"\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(\"\\\"1\\\"\");\n+ assertThat(count, is(0));\n+\n+ count = realm.users().count(\"\\\"\\\"\");\n+ assertThat(count, is(0));\n+\n+ count = realm.users().count(\"\\\"user1FirstName\\\"\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(\"\\\"user1LastName\\\"\");\n+ assertThat(count, is(1));\n+\n+ count = realm.users().count(\"\\\"[email protected]\\\"\");\n+ assertThat(count, is(1));\n}\n@Test\n@@ -184,13 +239,13 @@ public class UsersTest extends AbstractAdminTest {\n//search all\nassertThat(testRealmResource.users().count(\"user\"), is(3));\n//search first name\n- assertThat(testRealmResource.users().count(\"FirstName\"), is(3));\n+ assertThat(testRealmResource.users().count(\"*FirstName*\"), is(3));\nassertThat(testRealmResource.users().count(\"user2FirstName\"), is(1));\n//search last name\n- assertThat(testRealmResource.users().count(\"LastName\"), is(3));\n+ assertThat(testRealmResource.users().count(\"*LastName*\"), is(3));\nassertThat(testRealmResource.users().count(\"user2LastName\"), is(1));\n//search in email\n- assertThat(testRealmResource.users().count(\"@example.com\"), is(3));\n+ assertThat(testRealmResource.users().count(\"*@example.com*\"), is(3));\nassertThat(testRealmResource.users().count(\"[email protected]\"), is(1));\n//search for something not existing\nassertThat(testRealmResource.users().count(\"notExisting\"), is(0));\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-18727 Improve user search query
339,511
10.01.2022 18:19:11
-32,400
ef134390c2f6258d8857abb7244b19b70966c9a9
Client Policies : Condition's negative logic configuration is not shown in Admin Console's form view Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "server-spi-private/src/main/java/org/keycloak/services/clientpolicy/condition/AbstractClientPolicyConditionProviderFactory.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.services.clientpolicy.condition;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+import org.keycloak.Config.Scope;\n+import org.keycloak.models.KeycloakSessionFactory;\n+import org.keycloak.provider.ProviderConfigProperty;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n+ */\n+public abstract class AbstractClientPolicyConditionProviderFactory implements ClientPolicyConditionProviderFactory {\n+\n+ public static final String IS_NEGATIVE_LOGIC = \"is-negative-logic\";\n+\n+ static protected void addCommonConfigProperties(List<ProviderConfigProperty> configProperties) {\n+ ProviderConfigProperty property = new ProviderConfigProperty(IS_NEGATIVE_LOGIC, \"Negative Logic\",\n+ \"If On, the result of condition's evaluation is reverted from true to false and vice versa.\",\n+ ProviderConfigProperty.BOOLEAN_TYPE, false);\n+ configProperties.add(property);\n+ }\n+\n+ @Override\n+ public void init(Scope config) {\n+ }\n+\n+ @Override\n+ public void postInit(KeycloakSessionFactory factory) {\n+ }\n+\n+ @Override\n+ public void close() {\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/AnyClientConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/AnyClientConditionFactory.java", "diff": "package org.keycloak.services.clientpolicy.condition;\n-import java.util.Collections;\n+import java.util.ArrayList;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class AnyClientConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class AnyClientConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"any-client\";\n- @Override\n- public ClientPolicyConditionProvider create(KeycloakSession session) {\n- return new AnyClientCondition(session);\n- }\n-\n- @Override\n- public void init(Scope config) {\n- }\n+ private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n+ static {\n+ addCommonConfigProperties(configProperties);\n}\n@Override\n- public void close() {\n+ public ClientPolicyConditionProvider create(KeycloakSession session) {\n+ return new AnyClientCondition(session);\n}\n@Override\n@@ -59,9 +51,9 @@ public class AnyClientConditionFactory implements ClientPolicyConditionProviderF\nreturn \"The condition is satisfied by any client on any event.\";\n}\n+\n@Override\npublic List<ProviderConfigProperty> getConfigProperties() {\n- return Collections.emptyList();\n+ return configProperties;\n}\n-\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientAccessTypeConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientAccessTypeConditionFactory.java", "diff": "@@ -21,15 +21,13 @@ import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class ClientAccessTypeConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class ClientAccessTypeConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"client-access-type\";\n@@ -42,6 +40,8 @@ public class ClientAccessTypeConditionFactory implements ClientPolicyConditionPr\nprivate static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\nstatic {\n+ addCommonConfigProperties(configProperties);\n+\nProviderConfigProperty property;\nproperty = new ProviderConfigProperty(TYPE, \"client-accesstype.label\", \"client-accesstype.tooltip\", ProviderConfigProperty.MULTIVALUED_LIST_TYPE, TYPE_CONFIDENTIAL);\nList<String> updateProfileValues = Arrays.asList(TYPE_CONFIDENTIAL, TYPE_PUBLIC, TYPE_BEARERONLY);\n@@ -54,18 +54,6 @@ public class ClientAccessTypeConditionFactory implements ClientPolicyConditionPr\nreturn new ClientAccessTypeCondition(session);\n}\n- @Override\n- public void init(Scope config) {\n- }\n-\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n- }\n-\n- @Override\n- public void close() {\n- }\n-\n@Override\npublic String getId() {\nreturn PROVIDER_ID;\n@@ -80,5 +68,4 @@ public class ClientAccessTypeConditionFactory implements ClientPolicyConditionPr\npublic List<ProviderConfigProperty> getConfigProperties() {\nreturn configProperties;\n}\n-\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientRolesConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientRolesConditionFactory.java", "diff": "@@ -20,15 +20,13 @@ package org.keycloak.services.clientpolicy.condition;\nimport java.util.ArrayList;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class ClientRolesConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class ClientRolesConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"client-roles\";\n@@ -37,6 +35,8 @@ public class ClientRolesConditionFactory implements ClientPolicyConditionProvide\nprivate static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\nstatic {\n+ addCommonConfigProperties(configProperties);\n+\nProviderConfigProperty property;\nproperty = new ProviderConfigProperty(ROLES, PROVIDER_ID + \".label\", PROVIDER_ID + \"-condition.tooltip\", ProviderConfigProperty.MULTIVALUED_STRING_TYPE, null);\nconfigProperties.add(property);\n@@ -47,18 +47,6 @@ public class ClientRolesConditionFactory implements ClientPolicyConditionProvide\nreturn new ClientRolesCondition(session);\n}\n- @Override\n- public void init(Scope config) {\n- }\n-\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n- }\n-\n- @Override\n- public void close() {\n- }\n-\n@Override\npublic String getId() {\nreturn PROVIDER_ID;\n@@ -73,5 +61,4 @@ public class ClientRolesConditionFactory implements ClientPolicyConditionProvide\npublic List<ProviderConfigProperty> getConfigProperties() {\nreturn configProperties;\n}\n-\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientScopesConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientScopesConditionFactory.java", "diff": "@@ -21,16 +21,14 @@ import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.OAuth2Constants;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class ClientScopesConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class ClientScopesConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"client-scopes\";\n@@ -42,6 +40,8 @@ public class ClientScopesConditionFactory implements ClientPolicyConditionProvid\nprivate static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\nstatic {\n+ addCommonConfigProperties(configProperties);\n+\nProviderConfigProperty property = new ProviderConfigProperty(SCOPES, PROVIDER_ID + \"-condition.label\", PROVIDER_ID + \"-condition.tooltip\", ProviderConfigProperty.MULTIVALUED_STRING_TYPE, OAuth2Constants.OFFLINE_ACCESS);\nconfigProperties.add(property);\nproperty = new ProviderConfigProperty(TYPE, \"Scope Type\",\n@@ -57,18 +57,6 @@ public class ClientScopesConditionFactory implements ClientPolicyConditionProvid\nreturn new ClientScopesCondition(session);\n}\n- @Override\n- public void init(Scope config) {\n- }\n-\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n- }\n-\n- @Override\n- public void close() {\n- }\n-\n@Override\npublic String getId() {\nreturn PROVIDER_ID;\n@@ -83,5 +71,4 @@ public class ClientScopesConditionFactory implements ClientPolicyConditionProvid\npublic List<ProviderConfigProperty> getConfigProperties() {\nreturn configProperties;\n}\n-\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterContextConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterContextConditionFactory.java", "diff": "@@ -21,15 +21,13 @@ import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class ClientUpdaterContextConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class ClientUpdaterContextConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"client-updater-context\";\n@@ -43,6 +41,8 @@ public class ClientUpdaterContextConditionFactory implements ClientPolicyConditi\nprivate static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\nstatic {\n+ addCommonConfigProperties(configProperties);\n+\nProviderConfigProperty property;\nproperty = new ProviderConfigProperty(UPDATE_CLIENT_SOURCE, \"Update Client Context\", \"Specifies the context how is client created or updated. \" +\n\"ByInitialAccessToken is usually OpenID Connect client registration with the initial access token. \" +\n@@ -59,18 +59,6 @@ public class ClientUpdaterContextConditionFactory implements ClientPolicyConditi\nreturn new ClientUpdaterContextCondition(session);\n}\n- @Override\n- public void init(Scope config) {\n- }\n-\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n- }\n-\n- @Override\n- public void close() {\n- }\n-\n@Override\npublic String getId() {\nreturn PROVIDER_ID;\n@@ -85,5 +73,4 @@ public class ClientUpdaterContextConditionFactory implements ClientPolicyConditi\npublic List<ProviderConfigProperty> getConfigProperties() {\nreturn configProperties;\n}\n-\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterSourceGroupsConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterSourceGroupsConditionFactory.java", "diff": "@@ -20,15 +20,13 @@ package org.keycloak.services.clientpolicy.condition;\nimport java.util.ArrayList;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class ClientUpdaterSourceGroupsConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class ClientUpdaterSourceGroupsConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"client-updater-source-groups\";\n@@ -37,6 +35,8 @@ public class ClientUpdaterSourceGroupsConditionFactory implements ClientPolicyCo\nprivate static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\nstatic {\n+ addCommonConfigProperties(configProperties);\n+\nProviderConfigProperty property;\nproperty = new ProviderConfigProperty(GROUPS, PROVIDER_ID + \".label\", PROVIDER_ID + \".tooltip\", ProviderConfigProperty.MULTIVALUED_STRING_TYPE, \"topGroup\");\nconfigProperties.add(property);\n@@ -47,18 +47,6 @@ public class ClientUpdaterSourceGroupsConditionFactory implements ClientPolicyCo\nreturn new ClientUpdaterSourceGroupsCondition(session);\n}\n- @Override\n- public void init(Scope config) {\n- }\n-\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n- }\n-\n- @Override\n- public void close() {\n- }\n-\n@Override\npublic String getId() {\nreturn PROVIDER_ID;\n@@ -73,5 +61,4 @@ public class ClientUpdaterSourceGroupsConditionFactory implements ClientPolicyCo\npublic List<ProviderConfigProperty> getConfigProperties() {\nreturn configProperties;\n}\n-\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterSourceHostsConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterSourceHostsConditionFactory.java", "diff": "package org.keycloak.services.clientpolicy.condition;\n-import java.util.Arrays;\n+import java.util.ArrayList;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class ClientUpdaterSourceHostsConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class ClientUpdaterSourceHostsConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"client-updater-source-host\";\npublic static final String TRUSTED_HOSTS = \"trusted-hosts\";\n- private static final ProviderConfigProperty TRUSTED_HOSTS_PROPERTY = new ProviderConfigProperty(TRUSTED_HOSTS, \"client-updater-trusted-hosts.label\",\n- \"client-updater-trusted-hosts.tooltip\", ProviderConfigProperty.MULTIVALUED_STRING_TYPE, null);\n+ private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\n- @Override\n- public ClientPolicyConditionProvider create(KeycloakSession session) {\n- return new ClientUpdaterSourceHostsCondition(session);\n- }\n+ static {\n+ addCommonConfigProperties(configProperties);\n- @Override\n- public void init(Scope config) {\n- }\n-\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n+ ProviderConfigProperty property;\n+ property = new ProviderConfigProperty(TRUSTED_HOSTS, \"client-updater-trusted-hosts.label\",\n+ \"client-updater-trusted-hosts.tooltip\", ProviderConfigProperty.MULTIVALUED_STRING_TYPE, null);\n+ configProperties.add(property);\n}\n@Override\n- public void close() {\n+ public ClientPolicyConditionProvider create(KeycloakSession session) {\n+ return new ClientUpdaterSourceHostsCondition(session);\n}\n@Override\n@@ -66,7 +60,6 @@ public class ClientUpdaterSourceHostsConditionFactory implements ClientPolicyCon\n@Override\npublic List<ProviderConfigProperty> getConfigProperties() {\n- return Arrays.asList(TRUSTED_HOSTS_PROPERTY);\n+ return configProperties;\n}\n-\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterSourceRolesConditionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterSourceRolesConditionFactory.java", "diff": "@@ -20,15 +20,13 @@ package org.keycloak.services.clientpolicy.condition;\nimport java.util.ArrayList;\nimport java.util.List;\n-import org.keycloak.Config.Scope;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\n/**\n* @author <a href=\"mailto:[email protected]\">Takashi Norimatsu</a>\n*/\n-public class ClientUpdaterSourceRolesConditionFactory implements ClientPolicyConditionProviderFactory {\n+public class ClientUpdaterSourceRolesConditionFactory extends AbstractClientPolicyConditionProviderFactory {\npublic static final String PROVIDER_ID = \"client-updater-source-roles\";\n@@ -37,6 +35,8 @@ public class ClientUpdaterSourceRolesConditionFactory implements ClientPolicyCon\nprivate static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();\nstatic {\n+ addCommonConfigProperties(configProperties);\n+\nProviderConfigProperty property;\nproperty = new ProviderConfigProperty(ROLES, PROVIDER_ID + \".label\", PROVIDER_ID + \".tooltip\", ProviderConfigProperty.MULTIVALUED_STRING_TYPE, \"admin\");\nconfigProperties.add(property);\n@@ -47,18 +47,6 @@ public class ClientUpdaterSourceRolesConditionFactory implements ClientPolicyCon\nreturn new ClientUpdaterSourceRolesCondition(session);\n}\n- @Override\n- public void init(Scope config) {\n- }\n-\n- @Override\n- public void postInit(KeycloakSessionFactory factory) {\n- }\n-\n- @Override\n- public void close() {\n- }\n-\n@Override\npublic String getId() {\nreturn PROVIDER_ID;\n@@ -67,12 +55,10 @@ public class ClientUpdaterSourceRolesConditionFactory implements ClientPolicyCon\n@Override\npublic String getHelpText() {\nreturn \"The condition checks the role of the entity who tries to create/update the client to determine whether the policy is applied.\";\n-\n}\n@Override\npublic List<ProviderConfigProperty> getConfigProperties() {\nreturn configProperties;\n}\n-\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Client Policies : Condition's negative logic configuration is not shown in Admin Console's form view Closes #9447
339,618
27.01.2022 10:03:11
-3,600
0f082dde5b7db71e69bb4727360aea6d4c2ed3aa
fix relevant options for existing guides closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/db.adoc", "new_path": "docs/guides/src/main/server/db.adoc", "diff": "title=\"Relational database setup\"\nsummary=\"Understand how to configure different relational databases for Keycloak\"\npriority=10\n- includedOptions=\"db db.* hostname\">\n+ includedOptions=\"db db-* hostname\">\nFirst step is to decide which database vendor you are going to use. Keycloak has support for a number of different vendors.\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/enabletls.adoc", "new_path": "docs/guides/src/main/server/enabletls.adoc", "diff": "<@tmpl.guide\ntitle=\"Configure TLS\"\nsummary=\"Learn how to configure Keycloak's https certificates for in- and outgoing requests as well as mTLS.\"\n-includedOptions=\"https.* http.enabled\">\n+includedOptions=\"https-* http-enabled\">\nTransport Layer Security (short: TLS) is crucial to exchange data over a secured channel. For production environments, you should never expose Keycloak endpoints through HTTP, as sensitive data is at the core of what Keycloak exchanges with other applications. In this guide you will learn how to configure Keycloak to use HTTPS/TLS.\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/proxy.adoc", "new_path": "docs/guides/src/main/server/proxy.adoc", "diff": "title=\"Configuring a reverse proxy\"\nsummary=\"Learn how to configure Keycloak together with a reverse proxy, api gateway or load balancer.\"\npriority=20\n-includedOptions=\"proxy proxy.*\">\n+includedOptions=\"proxy proxy-*\">\nIt is pretty common nowadays to use a reverse proxy in distributed environments. If you want to use Keycloak together with such a proxy, you can use different proxy modes depending on the TLS termination in your specific environment:\n" } ]
Java
Apache License 2.0
keycloak/keycloak
fix relevant options for existing guides (#9805) closes #9804
339,618
27.01.2022 11:17:22
-3,600
47ad9a29eb86bc0f6202500cf2b788791870fc45
Hostname Guide V1 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/guides/src/main/server/hostname.adoc", "diff": "+<#import \"/templates/guide.adoc\" as tmpl>\n+<#import \"/templates/kc.adoc\" as kc>\n+<#import \"/templates/links.adoc\" as links>\n+\n+<@tmpl.guide\n+title=\"Configure the Hostname\"\n+summary=\"Learn how to configure the frontend and backchannel endpoints exposed by Keycloak.\"\n+includedOptions=\"hostname-* proxy\">\n+\n+When running Keycloak in environments such as Kubernetes, OpenShift or even on-premise, you usually do not want to expose the internal URLs to the public facing internet. Instead, you want to use your public hostname. This guide will show you how to configure Keycloak to use the right hostname for different scenarios.\n+\n+== Keycloak API Endpoint categories\n+Keycloak exposes three different API endpoint categories, each using a specific base URL. These categories are:\n+\n+=== Frontend Endpoints\n+Frontend endpoints are used to externally access Keycloak. When no Hostname is set, the base URL used for the frontend is taken from the incoming request. This has some major disadvantages, e.g. in High availability setups spanning multiple Keycloak instances, where it should not depend on the instance the request lands what URL is used, but instead one URL should be used for all instances, so they are seen as one system from the outside.\n+\n+The `hostname` property can be used to set the hostname part of the frontend base URL:\n+\n+<@kc.start parameters=\"--hostname=<value>\"/>\n+\n+=== Backend Endpoints\n+Backend endpoints are used for direct communication between Keycloak and applications. Examples are the Token endpoint or the User info endpoint. Backend endpoints are also taking the base URL from the request by default. To override this behaviour, set the `hostname-strict-backchannel` configuration option:\n+\n+<@kc.start parameters=\"--hostname=<value> --hostname-strict-backchannel=true\"/>\n+\n+When all applications connected to Keycloak communicate through the public URL, set `hostname-strict-backchannel` to true. Otherwise, leave it as false to allow internal applications to communicate with Keycloak through an internal URL\n+\n+=== Administrative Endpoints\n+When the admin console is exposed on a different hostname, use `--hostname-admin` to link to it:\n+\n+<@kc.start parameters=\"--hostname=<hostname> --hostname-admin=<adminHostname>\"/>\n+\n+When `hostname-admin` is configured, all links and static resources used to render the admin console are served from the value you enter for `<adminHostname>` instead of using `<hostname>`.\n+\n+Keycloaks administration endpoints and its admin console should not be publicly accessible at all to reduce attack surface, so you might want to secure them using a reverse proxy. For more information about which paths to expose using a reverse proxy, please refer to the <@links.server id=\"proxy\"/> Guide.\n+\n+== Overriding the hostname path\n+When running behind a reverse proxy, you may expose Keycloak using a different context path such as `myproxy.url/mykeycloak`. To do this, you can override the hostname path to use the path defined in your reverse proxy:\n+\n+<@kc.start parameters=\"--hostname=myurl --hostname-path=mykeycloak\"/>\n+\n+\n+The `hostname-path` configuration only takes effect when a reverse proxy is enabled. Please see the <@links.server id=\"proxy\"/> Guide for details.\n+\n+== Using the hostname in development mode\n+When running Keycloak in development mode by using `start-dev`, the hostname setting is optional. When the `hostname` is not specified the incoming request headers will be used.\n+\n+=== Example: Hostname in development mode\n+.Keycloak configuration:\n+<@kc.startdev parameters=\"\"/>\n+\n+.Invoked command:\n+[source, bash]\n+----\n+curl GET \"https://localhost:8080/realms/master/.well-known/openid-configuration\" | jq .\n+----\n+\n+.Result:\n+[source, bash]\n+----\n+# Frontend endpoints: request://request:request -> http://localhost:8080\n+# Backend endpoints: request://request:request -> http://localhost:8080\n+----\n+\n+Invoking the curl GET request above when running in development mode will show you the current OpenID Discovery configuration. In this configuration, all base URLS will be taken from the incoming request, so `http://localhost:8080` will be used for all endpoints.\n+\n+== Example Scenarios\n+Here are a few more example scenarios and the corresponding commands for setting up a hostname.\n+\n+=== Assumptions for all scenarios\n+* Keycloak is set up using HTTPS certificates and Port 8443.\n+* `intlUrl` refers to an internal IP/DNS for Keycloak\n+* `myUrl` refers to an exposed public URL\n+* Keycloak runs in production mode using the `start` command\n+\n+=== Example 1: Hostname configuration without reverse proxy\n+.Keycloak configuration:\n+<@kc.start parameters=\"--hostname=myurl\"/>\n+\n+.Invoked command:\n+[source, bash]\n+----\n+curl GET \"https://intUrl:8443/realms/master/.well-known/openid-configuration\" | jq .\n+----\n+\n+.Result:\n+[source, bash]\n+----\n+# Frontend Endpoints: request://myurl:request -> https://myurl:8443\n+# Backend Endpoints: request://request:request -> https://internal:8443\n+----\n+\n+=== Example 2: Hostname configuration without reverse proxy - strict backchannel enabled\n+\n+.Keycloak configuration:\n+<@kc.start parameters=\"--hostname=myurl --hostname-strict-backchannel=true\"/>\n+\n+.Invoked command:\n+[source, bash]\n+----\n+curl GET \"https://intUrl:8443/realms/master/.well-known/openid-configuration\" | jq .\n+----\n+\n+.Result:\n+[source, bash]\n+----\n+# Frontend: request://myurl:request -> https://myurl:8443\n+# Backend: request://myurl:request -> https://myurl:8443\n+----\n+\n+=== Example 3: Hostname configuration with reverse proxy\n+.Keycloak configuration:\n+<@kc.start parameters=\"--hostname=myurl --proxy=passthrough\"/>\n+\n+.Invoked command:\n+[source, bash]\n+----\n+curl GET \"https://intUrl:8443/realms/master/.well-known/openid-configuration\" | jq .\n+----\n+\n+.Result:\n+[source, bash]\n+----\n+# Frontend Endpoints: request://myurl -> https://myurl\n+# Backend Endpoints: request://request:request -> https://internal:8443\n+----\n+\n+=== Hostname configuration with reverse proxy and different path\n+.Keycloak configuration:\n+<@kc.start parameters=\"--hostname=myurl --proxy=passthrough --hostname-path=mykeycloak\"/>\n+\n+.Invoked command:\n+[source, bash]\n+----\n+curl GET \"https://intUrl:8443/realms/master/.well-known/openid-configuration\" | jq .\n+----\n+\n+.Result:\n+[source, bash]\n+----\n+# Frontend Endpoints: request://myurl -> https://myurl/mykeycloak\n+# Backend Endpoints: request://request:request -> https://internal:8443\n+----\n+\n+</@tmpl.guide>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/templates/kc.adoc", "new_path": "docs/guides/src/main/templates/kc.adoc", "diff": "@@ -11,3 +11,10 @@ bin/kc.[sh|bat] build ${parameters}\nbin/kc.[sh|bat] start ${parameters}\n----\n</#macro>\n+\n+<#macro startdev parameters>\n+[source,bash]\n+----\n+bin/kc.[sh|bat] start-dev ${parameters}\n+----\n+</#macro>\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Hostname Guide V1 (#9762) Closes #9460
339,618
27.01.2022 11:18:50
-3,600
6395e89cfca42d168b89da8e71df0e337daa5b66
Vault Guide v1 * Vault Guide v1 Containing only Kubernetes / OpenShift secrets via file based vault for now Closes * Apply suggestions from code review
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/guides/src/main/server/vault.adoc", "diff": "+<#import \"/templates/guide.adoc\" as tmpl>\n+<#import \"/templates/kc.adoc\" as kc>\n+\n+<@tmpl.guide\n+title=\"Using Kubernetes Secrets\"\n+summary=\"Learn how to use Kubernetes / OpenShift secrets in Keycloak\"\n+priority=30\n+includedOptions=\"vault vault-*\">\n+\n+Keycloak supports a file based vault implementation for Kubernetes / OpenShift secrets. Mount Kubernetes secrets into the Keycloak Container, and the data fields will be available in the mounted folder with a flat-file structure.\n+\n+== Available integrations\n+You can use Kubernetes / OpenShift secrets for the following use-cases:\n+\n+* Obtain the SMTP Mail server Password\n+* Obtain the LDAP Bind Credential when using LDAP-based User Federation\n+* Obtain the OIDC identity providers Client Secret when integrating external identity providers\n+\n+== Enabling the vault\n+Enable the file based vault by building Keycloak using the following build option:\n+\n+<@kc.build parameters=\"--vault=file\"/>\n+\n+== Setting the base directory to lookup secrets\n+Kubernetes / OpenShift secrets are basically mounted files, so you have to configure a directory for these files to be mounted in:\n+\n+<@kc.start parameters=\"--vault-dir=/my/path\"/>\n+\n+== Realm-specific secret files\n+Kubernetes / OpenShift Secrets are used per-realm basis in Keycloak, so there's a naming convention for the file in place:\n+[source, bash]\n+----\n+${r\"${vault.<realmname>_<secretname>}\"}\n+----\n+\n+=== Using underscores in the Name\n+In order to process the secret correctly, it is needed to double all underscores in the <realmname> or the <secretname>, separated by a single underscore.\n+\n+.Example\n+* Realm Name: `sso_realm`\n+* Desired Name: `ldap_credential`\n+* Resulting file Name:\n+[source, bash]\n+----\n+sso__realm_ldap__credential\n+----\n+Note the doubled underscores between __sso__ and __realm__ and also between __ldap__ and __credential__.\n+\n+== Example: Use an LDAP bind credential secret in the admin console\n+\n+.Example setup\n+* A realm named `secrettest`\n+* A desired Name `ldapBc` for the bind Credential\n+* Resulting file name: `secrettest_ldapBc`\n+\n+.Usage in admin console\n+You can then use this secret from the admin console by using `${r\"${vault.ldapBc}\"}` as value for the `Bind Credential` when configuring your LDAP User federation.\n+\n+</@tmpl.guide>\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Vault Guide v1 (#9772) * Vault Guide v1 Containing only Kubernetes / OpenShift secrets via file based vault for now Closes #9462 * Apply suggestions from code review Co-authored-by: Andrea Peruffo <[email protected]> Co-authored-by: Andrea Peruffo <[email protected]>
339,618
27.01.2022 14:57:18
-3,600
f70a22f58316b434178b8e3c59b1e45255e9fd13
Run from Container guide V1 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/guides/src/main/server/containers.adoc", "diff": "+<#import \"/templates/guide.adoc\" as tmpl>\n+<#import \"/templates/kc.adoc\" as kc>\n+<#import \"/templates/options.adoc\" as opts>\n+<#import \"/templates/links.adoc\" as links>\n+\n+<@tmpl.guide\n+title=\"Running in a container\"\n+summary=\"Learn how to run Keycloak from a container image\"\n+priority=20\n+includedOptions=\"db db-url db-username db-password features hostname https-key-store-file https-key-store-password metrics-enabled\">\n+\n+Keycloak is handling containerized environments like Kubernetes or OpenShift as first-class-citizens. In this guide you'll learn how to run and optimize the Keycloak container image to have the best experience running a Keycloak container.\n+\n+== Create an optimized container image\n+To get the best startup experience for your Keycloak container, we recommend building an optimized container image by running the `build` step explicitly before starting:\n+\n+=== Build your optimized Keycloak docker image\n+The `Dockerfile` below creates a pre-configured Keycloak image which enables the metrics endpoint, the token exchange feature and uses a postgres database.\n+\n+.Dockerfile:\n+[source, dockerfile]\n+----\n+FROM quay.io/keycloak/keycloak-x:latest as builder\n+\n+ENV KC_METRICS_ENABLED=true\n+ENV KC_FEATURES=token-exchange\n+ENV KC_DB=postgres\n+RUN /opt/keycloak/bin/kc.sh build\n+\n+FROM quay.io/keycloak/keycloak-x:latest\n+COPY --from=builder /opt/keycloak/lib/quarkus/ /opt/keycloak/lib/quarkus/\n+WORKDIR /opt/keycloak\n+# for demonstration purposes only, please make sure to use proper certificates in production instead\n+RUN keytool -genkeypair -storepass password -storetype PKCS12 -keyalg RSA -keysize 2048 -dname \"CN=server\" -alias server -ext \"SAN:c=DNS:localhost,IP:127.0.0.1\" -keystore conf/server.keystore\n+ENV KEYCLOAK_ADMIN=admin\n+ENV KEYCLOAK_ADMIN_PASSWORD=change_me\n+# change these values to point to a running postgres instance\n+ENV KC_DB_URL=<DBURL>\n+ENV KC_DB_USERNAME=<DBUSERNAME>\n+ENV KC_DB_PASSWORD=<DBPASSWORD>\n+ENV KC_HOSTNAME=localhost:8443\n+ENTRYPOINT [\"/opt/keycloak/bin/kc.sh\", \"start\"]\n+----\n+In the first stage of this multi-staged build, we're creating the optimized image using the `build` command to apply the build options. From the `builder`, we're copying the files generated by the `build` process into a new image. In this runner image, we apply the specific run configuration, containing e.g. a keystore, the environment-specific hostname configuration and database configuration. Then this image gets started in production mode by using the `start` command in the entrypoint.\n+\n+Note that this example uses a multi-staged build to explicitly showcase the build and run steps. It could also be run as a single-staged docker build.\n+\n+=== Building the docker image\n+To build the actual docker image, run the following command form the Directory containing your Dockerfile:\n+[source,bash]\n+----\n+podman|docker build . -t prebuilt_keycloak\n+----\n+\n+=== Start the optimized Keycloak docker image:\n+To start the image, run:\n+[source, bash]\n+----\n+podman|docker run --name optimized_keycloak -p 8443:8443 prebuilt_keycloak\n+----\n+Keycloak starts up in production mode, using only secured HTTPS communication, and is available on `https://localhost:8443`.\n+You'll notice that the startup log contains the following line:\n+[source, bash]\n+----\n+INFO [org.key.com.Profile] (main) Preview feature enabled: token_exchange\n+----\n+This shows the desired feature is enabled.\n+\n+Opening up `https://localhost:8443/metrics` leads to a page containing operational metrics which could be used by your monitoring solution.\n+\n+== Try Keycloak out in development mode\n+The easiest way to try out Keycloak from a container for development or testing purposes is using the Development mode by using the `start-dev` command:\n+\n+[source,bash]\n+----\n+podman|docker run --name keycloak_test -p 8080:8080 \\\n+ -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=change_me \\\n+ quay.io/keycloak/keycloak-x:latest \\\n+ start-dev\n+----\n+\n+Invoking this command will spin up the Keycloak server in development mode.\n+\n+Keep in mind that this mode is by no means meant to be used in production environments, as it has insecure defaults. For more information about running Keycloak in production, see _todo_link_to_running_in_production_guide_.\n+\n+== Use auto-build to run a standard keycloak container\n+Following concepts such as immutable infrastructure, containers need to be re-provisioned fairly often. In these environments, you want to have containers which start up fast by using an optimized image as described above.\n+\n+However, when your environment is different, you may want to run a standard Keycloak image using the `--auto-build` flag like below:\n+\n+[source, bash]\n+----\n+podman|docker run --name keycloak_auto_build -p 8080:8080 \\\n+ -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=change_me \\\n+ quay.io/keycloak/keycloak-x:latest \\\n+ start \\\n+ --auto-build \\\n+ --db=postgres --features=token-exchange \\\n+ --db-url=<JDBC-URL> --db-username=<DB-USER> --db-password=<DB-PASSWORD> \\\n+ --https-key-store-file=<file> --https-key-store-password=<password>\n+----\n+\n+Running the above will spin up a Keycloak server which detects and applies the build configuration first. In the example, it's `--db=postgres --features=token-exchange` to set the used database vendor to postgres and enable the token exchange feature.\n+\n+Keycloak will then start up and apply the configuration for the specific environment. This approach results in a significantly bigger startup time, and an image that is mutable, and is therefor not the best practice.\n+\n+</@tmpl.guide>\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/enabletls.adoc", "new_path": "docs/guides/src/main/server/enabletls.adoc", "diff": "@@ -34,7 +34,7 @@ By default, Keycloak does not enable deprecated TLS protocols. In situations whe\n<@kc.start parameters=\"--https-protocols=<protocol>[,<protocol>]\"/>\n-To also allow TLSv1.2, use for example `kc.sh start --http-protocols=TLSv1.3,TLSv1.2`.\n+To also allow TLSv1.2, use for example `kc.sh start --https-protocols=TLSv1.3,TLSv1.2`.\n== Switch the HTTPS port\nKeycloak listens for HTTPS traffic on port `8443` by default. To change this port, use:\n@@ -52,6 +52,6 @@ You can set a secure password for your truststore using the `https.trust-store.p\nIf no password is set, the default password `password` is used.\n== Securing credentials\n-We recommend to not set any password in plaintext via the CLI or in `conf/keycloak.properties`, but instead using good practices such as using a vault / mounted secret. Please refer to the Vault Guide / Production deployment guide for more advice.\n+We recommend to not set any password in plaintext via the CLI or in `conf/keycloak.conf`, but instead using good practices such as using a vault / mounted secret. Please refer to the Vault Guide / Production deployment guide for more advice.\n</@tmpl.guide>\n\\ No newline at end of file\n" }, { "change_type": "RENAME", "old_path": "docs/guides/src/main/server/proxy.adoc", "new_path": "docs/guides/src/main/server/reverseproxy.adoc", "diff": "" } ]
Java
Apache License 2.0
keycloak/keycloak
Run from Container guide V1 (#9646) Closes #9465 Co-authored-by: Stian Thorgersen <[email protected]> Co-authored-by: Stian Thorgersen <[email protected]>
339,410
27.01.2022 14:41:22
-3,600
2b81e62b6b62f7ce6f6e3918bf0a237cc52d9b9a
Adding workaround for deadlock in tests for Infinispan 12.1.7 Closes
[ { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanClusterProviderFactory.java", "new_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanClusterProviderFactory.java", "diff": "@@ -32,6 +32,7 @@ import org.keycloak.cluster.ClusterProvider;\nimport org.keycloak.cluster.ClusterProviderFactory;\nimport org.keycloak.common.util.Retry;\nimport org.keycloak.common.util.Time;\n+import org.keycloak.connections.infinispan.DefaultInfinispanConnectionProviderFactory;\nimport org.keycloak.connections.infinispan.InfinispanConnectionProvider;\nimport org.keycloak.connections.infinispan.TopologyInfo;\nimport org.keycloak.models.KeycloakSession;\n@@ -70,7 +71,13 @@ public class InfinispanClusterProviderFactory implements ClusterProviderFactory\n// Just to extract notifications related stuff to separate class\nprivate InfinispanNotificationsManager notificationsManager;\n- private ExecutorService localExecutor = Executors.newCachedThreadPool();\n+ private ExecutorService localExecutor = Executors.newCachedThreadPool(r -> {\n+ Thread thread = Executors.defaultThreadFactory().newThread(r);\n+ thread.setName(this.getClass().getName() + \"-\" + thread.getName());\n+ return thread;\n+ });\n+\n+ private ViewChangeListener workCacheListener;\n@Override\npublic ClusterProvider create(KeycloakSession session) {\n@@ -86,7 +93,8 @@ public class InfinispanClusterProviderFactory implements ClusterProviderFactory\nInfinispanConnectionProvider ispnConnections = session.getProvider(InfinispanConnectionProvider.class);\nworkCache = ispnConnections.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);\n- workCache.getCacheManager().addListener(new ViewChangeListener());\n+ workCacheListener = new ViewChangeListener();\n+ workCache.getCacheManager().addListener(workCacheListener);\n// See if we have RemoteStore (external JDG) configured for cross-Data-Center scenario\nSet<RemoteStore> remoteStores = InfinispanUtil.getRemoteStores(workCache);\n@@ -168,7 +176,13 @@ public class InfinispanClusterProviderFactory implements ClusterProviderFactory\n@Override\npublic void close() {\n-\n+ synchronized (this) {\n+ if (workCache != null && workCacheListener != null) {\n+ workCache.removeListener(workCacheListener);\n+ workCacheListener = null;\n+ localExecutor.shutdown();\n+ }\n+ }\n}\n@Override\n@@ -200,9 +214,16 @@ public class InfinispanClusterProviderFactory implements ClusterProviderFactory\n}\nlogger.debugf(\"Nodes %s removed from cluster. Removing tasks locked by this nodes\", removedNodesAddresses.toString());\n-\n+ /*\n+ workaround for Infinispan 12.1.7.Final to prevent a deadlock while\n+ DefaultInfinispanConnectionProviderFactory is shutting down PersistenceManagerImpl\n+ that acquires a writeLock and this removal that acquires a readLock.\n+ https://issues.redhat.com/browse/ISPN-13664\n+ */\n+ synchronized (DefaultInfinispanConnectionProviderFactory.class) {\nworkCache.entrySet().removeIf(new LockEntryPredicate(removedNodesAddresses));\n}\n+ }\n});\n}\n" }, { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanNotificationsManager.java", "new_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanNotificationsManager.java", "diff": "@@ -51,6 +51,7 @@ import org.keycloak.cluster.ClusterListener;\nimport org.keycloak.cluster.ClusterProvider;\nimport org.keycloak.common.util.ConcurrentMultivaluedHashMap;\nimport org.keycloak.common.util.Retry;\n+import org.keycloak.connections.infinispan.DefaultInfinispanConnectionProviderFactory;\nimport org.keycloak.executors.ExecutorsProvider;\nimport org.keycloak.models.KeycloakSession;\nimport org.infinispan.client.hotrod.exceptions.HotRodClientException;\n@@ -157,7 +158,15 @@ public class InfinispanNotificationsManager {\n// Add directly to remoteCache. Will notify remote listeners on all nodes in all DCs\nRetry.executeWithBackoff((int iteration) -> {\ntry {\n+ /*\n+ workaround for Infinispan 12.1.7.Final to prevent a deadlock while\n+ DefaultInfinispanConnectionProviderFactory is shutting down PersistenceManagerImpl\n+ that acquires a writeLock and this put that acquires a readLock.\n+ https://issues.redhat.com/browse/ISPN-13664\n+ */\n+ synchronized (DefaultInfinispanConnectionProviderFactory.class) {\nworkRemoteCache.put(eventKey, wrappedEvent, 120, TimeUnit.SECONDS);\n+ }\n} catch (HotRodClientException re) {\nif (logger.isDebugEnabled()) {\nlogger.debugf(re, \"Failed sending notification to remote cache '%s'. Key: '%s', iteration '%s'. Will try to retry the task\",\n@@ -231,7 +240,16 @@ public class InfinispanNotificationsManager {\ntry {\nlistenersExecutor.submit(() -> {\n- Object value = remoteCache.get(key);\n+ /*\n+ workaround for Infinispan 12.1.7.Final to prevent a deadlock while\n+ DefaultInfinispanConnectionProviderFactory is shutting down PersistenceManagerImpl\n+ that acquires a writeLock and this get that acquires a readLock.\n+ https://issues.redhat.com/browse/ISPN-13664\n+ */\n+ Object value;\n+ synchronized (DefaultInfinispanConnectionProviderFactory.class) {\n+ value = remoteCache.get(key);\n+ }\neventReceived(key, (Serializable) value);\n});\n" }, { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/connections/infinispan/DefaultInfinispanConnectionProviderFactory.java", "new_path": "model/infinispan/src/main/java/org/keycloak/connections/infinispan/DefaultInfinispanConnectionProviderFactory.java", "diff": "@@ -52,12 +52,12 @@ import java.util.Iterator;\nimport java.util.ServiceLoader;\nimport java.util.concurrent.TimeUnit;\n-import static org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory.REALM_CLEAR_CACHE_EVENTS;\n-import static org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory.REALM_INVALIDATION_EVENTS;\nimport static org.keycloak.connections.infinispan.InfinispanUtil.configureTransport;\nimport static org.keycloak.connections.infinispan.InfinispanUtil.createCacheConfigurationBuilder;\nimport static org.keycloak.connections.infinispan.InfinispanUtil.getActionTokenCacheConfig;\nimport static org.keycloak.connections.infinispan.InfinispanUtil.setTimeServiceToKeycloakTime;\n+import static org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory.REALM_CLEAR_CACHE_EVENTS;\n+import static org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory.REALM_INVALIDATION_EVENTS;\n/**\n* @author <a href=\"mailto:[email protected]\">Stian Thorgersen</a>\n@@ -85,6 +85,13 @@ public class DefaultInfinispanConnectionProviderFactory implements InfinispanCon\n@Override\npublic void close() {\n+ /*\n+ workaround for Infinispan 12.1.7.Final to prevent a deadlock while\n+ DefaultInfinispanConnectionProviderFactory is shutting down PersistenceManagerImpl\n+ that acquires a writeLock and this removal that acquires a readLock.\n+ https://issues.redhat.com/browse/ISPN-13664\n+ */\n+ synchronized (DefaultInfinispanConnectionProviderFactory.class) {\nif (cacheManager != null && !containerManaged) {\ncacheManager.stop();\n}\n@@ -93,6 +100,7 @@ public class DefaultInfinispanConnectionProviderFactory implements InfinispanCon\n}\ncacheManager = null;\n}\n+ }\n@Override\npublic String getId() {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Adding workaround for deadlock in tests for Infinispan 12.1.7 Closes #9648
339,709
13.01.2022 08:28:00
-3,600
f11b049e524ab3e46e0b50985069fa71e45d58ca
Missing translation of webauthn-doAuthenticate added closes
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources-community/theme/base/login/messages/messages_de.properties", "new_path": "themes/src/main/resources-community/theme/base/login/messages/messages_de.properties", "diff": "@@ -354,6 +354,7 @@ webauthn-login-title=Security-Token Anmeldung\nwebauthn-registration-title=Security-Token Registrierung\nwebauthn-available-authenticators=Verf\\u00FCgbare Authentifikatoren\nwebauthn-unsupported-browser-text=WebAuthn wird von diesem Browser nicht unterst\\u00FCtzt. Versuchen Sie es mit einem anderen oder wenden Sie sich an Ihren Administrator.\n+webauthn-doAuthenticate=Anmelden mit Security-Token\n# WebAuthn Error\nwebauthn-error-title=Security-Token Fehler\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Missing translation of webauthn-doAuthenticate added closes #9424
339,410
27.01.2022 14:41:22
-3,600
64cbbde7cf255c853ba098f2cf3e899413ff4e0a
Adding workaround unstable tests due to Infinispan 12.1.7 Closes
[ { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/KeycloakModelTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/KeycloakModelTest.java", "diff": "@@ -59,6 +59,7 @@ import java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n+import java.util.concurrent.Semaphore;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\n@@ -331,7 +332,27 @@ public abstract class KeycloakModelTest {\npublic static void inIndependentFactories(int numThreads, int timeoutSeconds, Runnable task) throws InterruptedException {\nExecutorService es = Executors.newFixedThreadPool(numThreads);\ntry {\n- Callable<?> independentTask = () -> inIndependentFactory(() -> { task.run(); return null; });\n+ /*\n+ workaround for Infinispan 12.1.7.Final to prevent an internal Infinispan NullPointerException\n+ when multiple nodes tried to join at the same time by starting them sequentially with 1 sec delay.\n+ Already fixed in Infinispan 13.\n+ https://issues.redhat.com/browse/ISPN-13231\n+ */\n+ Semaphore sem = new Semaphore(1);\n+ Callable<?> independentTask = () -> {\n+ try {\n+ sem.acquire();\n+ return inIndependentFactory(() -> {\n+ Thread.sleep(1000);\n+ sem.release();\n+ task.run();\n+ return null;\n+ });\n+ } catch (Exception ex) {\n+ LOG.error(\"Thread terminated with an exception\", ex);\n+ return null;\n+ }\n+ };\nes.invokeAll(\nIntStream.range(0, numThreads)\n.mapToObj(i -> independentTask)\n@@ -339,7 +360,9 @@ public abstract class KeycloakModelTest {\ntimeoutSeconds, TimeUnit.SECONDS\n);\n} finally {\n- es.shutdownNow();\n+ LOG.debugf(\"waiting for threads to shutdown to avoid that one test pollutes another test\");\n+ es.shutdown();\n+ LOG.debugf(\"shutdown of threads complete\");\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/infinispan/CacheExpirationTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/infinispan/CacheExpirationTest.java", "diff": "@@ -80,7 +80,7 @@ public class CacheExpirationTest extends KeycloakModelTest {\nInfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\nCache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);\ndo {\n- try { Thread.sleep(1000); } catch (InterruptedException ex) {}\n+ try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n} while (! cache.getAdvancedCache().getDistributionManager().isJoinComplete());\ncache.keySet().forEach(s -> {});\n});\n@@ -102,7 +102,7 @@ public class CacheExpirationTest extends KeycloakModelTest {\n// Wait for at most 3 minutes which is much more than 15 seconds expiration set in DefaultInfinispanConnectionProviderFactory\nfor (int i = 0; i < 3 * 60; i++) {\n- try { Thread.sleep(1000); } catch (InterruptedException ex) {}\n+ try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\nif (getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class) == 0) {\nbreak;\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Adding workaround unstable tests due to Infinispan 12.1.7 Closes #9867
339,410
24.01.2022 14:59:34
-3,600
df7ddbf9b31c5f65560a793c7d4c76526779c33c
Added ModelIllegalStateException to handle lazy loading exception. Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaDelegateProvider.java", "diff": "+/*\n+ * Copyright 2022. Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.keycloak.models.map.storage.jpa;\n+\n+import org.keycloak.models.ModelIllegalStateException;\n+import org.keycloak.models.map.common.AbstractEntity;\n+\n+/**\n+ * Base class for all delegate providers for the JPA storage.\n+ *\n+ * Wraps the delegate so that it can be safely updated during lazy loading.\n+ */\n+public abstract class JpaDelegateProvider<T extends JpaRootEntity & AbstractEntity> {\n+ private T delegate;\n+\n+ protected JpaDelegateProvider(T delegate) {\n+ this.delegate = delegate;\n+ }\n+\n+ protected T getDelegate() {\n+ return delegate;\n+ }\n+\n+ /**\n+ * Validates the new entity.\n+ *\n+ * Will throw {@link ModelIllegalStateException} if the entity has been deleted or changed in the meantime.\n+ */\n+ protected void setDelegate(T newDelegate) {\n+ if (newDelegate == null) {\n+ throw new ModelIllegalStateException(\"Unable to retrieve entity: \" + delegate.getClass().getName() + \"#\" + delegate.getId());\n+ }\n+ if (newDelegate.getVersion() != delegate.getVersion()) {\n+ throw new ModelIllegalStateException(\"Version of entity changed between two loads: \" + delegate.getClass().getName() + \"#\" + delegate.getId());\n+ }\n+ this.delegate = newDelegate;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaRootEntity.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.keycloak.models.map.storage.jpa;\n+\n+/**\n+ * Interface for all root entities in the JPA storage.\n+ */\n+public interface JpaRootEntity {\n+\n+ /**\n+ * Version of the JPA entity used for optimistic locking\n+ */\n+ int getVersion();\n+}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/JpaClientMapKeycloakTransaction.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/JpaClientMapKeycloakTransaction.java", "diff": "@@ -76,6 +76,7 @@ public class JpaClientMapKeycloakTransaction extends JpaKeycloakTransaction impl\nRoot<JpaClientEntity> root = query.from(JpaClientEntity.class);\nquery.select(cb.construct(JpaClientEntity.class,\nroot.get(\"id\"),\n+ root.get(\"version\"),\nroot.get(\"entityVersion\"),\nroot.get(\"realmId\"),\nroot.get(\"clientId\"),\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/delegate/JpaClientDelegateProvider.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/delegate/JpaClientDelegateProvider.java", "diff": "@@ -28,21 +28,21 @@ import org.keycloak.models.map.client.MapClientEntity;\nimport org.keycloak.models.map.client.MapClientEntityFields;\nimport org.keycloak.models.map.common.EntityField;\nimport org.keycloak.models.map.common.delegate.DelegateProvider;\n+import org.keycloak.models.map.storage.jpa.JpaDelegateProvider;\nimport org.keycloak.models.map.storage.jpa.client.entity.JpaClientEntity;\n-public class JpaClientDelegateProvider implements DelegateProvider<MapClientEntity> {\n+public class JpaClientDelegateProvider extends JpaDelegateProvider<JpaClientEntity> implements DelegateProvider<MapClientEntity> {\n- private JpaClientEntity delegate;\nprivate final EntityManager em;\npublic JpaClientDelegateProvider(JpaClientEntity delegate, EntityManager em) {\n- this.delegate = delegate;\n+ super(delegate);\nthis.em = em;\n}\n@Override\npublic MapClientEntity getDelegate(boolean isRead, Enum<? extends EntityField<MapClientEntity>> field, Object... parameters) {\n- if (delegate.isMetadataInitialized()) return delegate;\n+ if (getDelegate().isMetadataInitialized()) return getDelegate();\nif (isRead) {\nif (field instanceof MapClientEntityFields) {\nswitch ((MapClientEntityFields) field) {\n@@ -51,26 +51,26 @@ public class JpaClientDelegateProvider implements DelegateProvider<MapClientEnti\ncase CLIENT_ID:\ncase PROTOCOL:\ncase ENABLED:\n- return delegate;\n+ return getDelegate();\ncase ATTRIBUTES:\nCriteriaBuilder cb = em.getCriteriaBuilder();\nCriteriaQuery<JpaClientEntity> query = cb.createQuery(JpaClientEntity.class);\nRoot<JpaClientEntity> root = query.from(JpaClientEntity.class);\nroot.fetch(\"attributes\", JoinType.INNER);\n- query.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(delegate.getId())));\n+ query.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(getDelegate().getId())));\n- delegate = em.createQuery(query).getSingleResult();\n+ setDelegate(em.createQuery(query).getSingleResult());\nbreak;\ndefault:\n- delegate = em.find(JpaClientEntity.class, UUID.fromString(delegate.getId()));\n+ setDelegate(em.find(JpaClientEntity.class, UUID.fromString(getDelegate().getId())));\n}\n} else throw new IllegalStateException(\"Not a valid client field: \" + field);\n} else {\n- delegate = em.find(JpaClientEntity.class, UUID.fromString(delegate.getId()));\n+ setDelegate(em.find(JpaClientEntity.class, UUID.fromString(getDelegate().getId())));\n}\n- return delegate;\n+ return getDelegate();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "diff": "@@ -45,6 +45,8 @@ import org.keycloak.models.map.client.MapClientEntity.AbstractClientEntity;\nimport org.keycloak.models.map.client.MapProtocolMapperEntity;\nimport org.keycloak.models.map.common.DeepCloner;\nimport static org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_CLIENT;\n+\n+import org.keycloak.models.map.storage.jpa.JpaRootEntity;\nimport org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n/**\n@@ -60,7 +62,7 @@ import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n)\n})\n@TypeDefs({@TypeDef(name = \"jsonb\", typeClass = JsonbType.class)})\n-public class JpaClientEntity extends AbstractClientEntity implements Serializable {\n+public class JpaClientEntity extends AbstractClientEntity implements Serializable, JpaRootEntity {\n@Id\n@Column\n@@ -113,9 +115,10 @@ public class JpaClientEntity extends AbstractClientEntity implements Serializabl\n* Used by hibernate when calling cb.construct from read(QueryParameters) method.\n* It is used to select client without metadata(json) field.\n*/\n- public JpaClientEntity(UUID id, Integer entityVersion, String realmId, String clientId,\n+ public JpaClientEntity(UUID id, int version, Integer entityVersion, String realmId, String clientId,\nString protocol, Boolean enabled) {\nthis.id = id;\n+ this.version = version;\nthis.entityVersion = entityVersion;\nthis.realmId = realmId;\nthis.clientId = clientId;\n@@ -148,6 +151,7 @@ public class JpaClientEntity extends AbstractClientEntity implements Serializabl\nmetadata.setEntityVersion(entityVersion);\n}\n+ @Override\npublic int getVersion() {\nreturn version;\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/JpaRoleMapKeycloakTransaction.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/JpaRoleMapKeycloakTransaction.java", "diff": "@@ -76,6 +76,7 @@ public class JpaRoleMapKeycloakTransaction extends JpaKeycloakTransaction implem\nRoot<JpaRoleEntity> root = query.from(JpaRoleEntity.class);\nquery.select(cb.construct(JpaRoleEntity.class,\nroot.get(\"id\"),\n+ root.get(\"version\"),\nroot.get(\"entityVersion\"),\nroot.get(\"realmId\"),\nroot.get(\"clientId\"),\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/delegate/JpaRoleDelegateProvider.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/delegate/JpaRoleDelegateProvider.java", "diff": "@@ -26,21 +26,21 @@ import org.keycloak.models.map.common.EntityField;\nimport org.keycloak.models.map.common.delegate.DelegateProvider;\nimport org.keycloak.models.map.role.MapRoleEntity;\nimport org.keycloak.models.map.role.MapRoleEntityFields;\n+import org.keycloak.models.map.storage.jpa.JpaDelegateProvider;\nimport org.keycloak.models.map.storage.jpa.role.entity.JpaRoleEntity;\n-public class JpaRoleDelegateProvider implements DelegateProvider<MapRoleEntity> {\n+public class JpaRoleDelegateProvider extends JpaDelegateProvider<JpaRoleEntity> implements DelegateProvider<MapRoleEntity> {\n- private JpaRoleEntity delegate;\nprivate final EntityManager em;\npublic JpaRoleDelegateProvider(JpaRoleEntity delegate, EntityManager em) {\n- this.delegate = delegate;\n+ super(delegate);\nthis.em = em;\n}\n@Override\npublic JpaRoleEntity getDelegate(boolean isRead, Enum<? extends EntityField<MapRoleEntity>> field, Object... parameters) {\n- if (delegate.isMetadataInitialized()) return delegate;\n+ if (getDelegate().isMetadataInitialized()) return getDelegate();\nif (isRead) {\nif (field instanceof MapRoleEntityFields) {\nswitch ((MapRoleEntityFields) field) {\n@@ -49,26 +49,26 @@ public class JpaRoleDelegateProvider implements DelegateProvider<MapRoleEntity>\ncase CLIENT_ID:\ncase NAME:\ncase DESCRIPTION:\n- return delegate;\n+ return getDelegate();\ncase ATTRIBUTES:\nCriteriaBuilder cb = em.getCriteriaBuilder();\nCriteriaQuery<JpaRoleEntity> query = cb.createQuery(JpaRoleEntity.class);\nRoot<JpaRoleEntity> root = query.from(JpaRoleEntity.class);\nroot.fetch(\"attributes\", JoinType.INNER);\n- query.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(delegate.getId())));\n+ query.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(getDelegate().getId())));\n- delegate = em.createQuery(query).getSingleResult();\n+ setDelegate(em.createQuery(query).getSingleResult());\nbreak;\ndefault:\n- delegate = em.find(JpaRoleEntity.class, UUID.fromString(delegate.getId()));\n+ setDelegate(em.find(JpaRoleEntity.class, UUID.fromString(getDelegate().getId())));\n}\n} else throw new IllegalStateException(\"Not a valid role field: \" + field);\n} else {\n- delegate = em.find(JpaRoleEntity.class, UUID.fromString(delegate.getId()));\n+ setDelegate(em.find(JpaRoleEntity.class, UUID.fromString(getDelegate().getId())));\n}\n- return delegate;\n+ return getDelegate();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "diff": "@@ -43,6 +43,8 @@ import org.hibernate.annotations.TypeDefs;\nimport org.keycloak.models.map.common.DeepCloner;\nimport org.keycloak.models.map.role.MapRoleEntity.AbstractRoleEntity;\nimport static org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_ROLE;\n+\n+import org.keycloak.models.map.storage.jpa.JpaRootEntity;\nimport org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n/**\n@@ -53,7 +55,7 @@ import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n@Entity\n@Table(name = \"role\", uniqueConstraints = {@UniqueConstraint(columnNames = {\"realmId\", \"clientId\", \"name\"})})\n@TypeDefs({@TypeDef(name = \"jsonb\", typeClass = JsonbType.class)})\n-public class JpaRoleEntity extends AbstractRoleEntity implements Serializable {\n+public class JpaRoleEntity extends AbstractRoleEntity implements Serializable, JpaRootEntity {\n@Id\n@Column\n@@ -106,8 +108,9 @@ public class JpaRoleEntity extends AbstractRoleEntity implements Serializable {\n* Used by hibernate when calling cb.construct from read(QueryParameters) method.\n* It is used to select role without metadata(json) field.\n*/\n- public JpaRoleEntity(UUID id, Integer entityVersion, String realmId, String clientId, String name, String description) {\n+ public JpaRoleEntity(UUID id, int version, Integer entityVersion, String realmId, String clientId, String name, String description) {\nthis.id = id;\n+ this.version = version;\nthis.entityVersion = entityVersion;\nthis.realmId = realmId;\nthis.clientId = clientId;\n@@ -140,6 +143,7 @@ public class JpaRoleEntity extends AbstractRoleEntity implements Serializable {\nmetadata.setEntityVersion(entityVersion);\n}\n+ @Override\npublic int getVersion() {\nreturn version;\n}\n" }, { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/models/delegate/ClientModelLazyDelegate.java", "new_path": "server-spi-private/src/main/java/org/keycloak/models/delegate/ClientModelLazyDelegate.java", "diff": "@@ -19,6 +19,7 @@ package org.keycloak.models.delegate;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.ClientScopeModel;\nimport org.keycloak.models.KeycloakSession;\n+import org.keycloak.models.ModelIllegalStateException;\nimport org.keycloak.models.ProtocolMapperModel;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.models.RoleModel;\n@@ -83,7 +84,7 @@ public class ClientModelLazyDelegate implements ClientModel {\n}\nClientModel ref = delegate.getReference();\nif (ref == null) {\n- throw new IllegalStateException(\"Invalid delegate obtained\");\n+ throw new ModelIllegalStateException(\"Invalid delegate obtained\");\n}\nreturn ref;\n}\n" }, { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java", "new_path": "server-spi-private/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java", "diff": "package org.keycloak.models.utils;\n+import org.jboss.logging.Logger;\nimport org.keycloak.authorization.AuthorizationProvider;\nimport org.keycloak.authorization.model.PermissionTicket;\nimport org.keycloak.authorization.model.Policy;\n@@ -46,8 +47,10 @@ import java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n+import java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\n+import java.util.function.Function;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n@@ -101,6 +104,7 @@ public class ModelToRepresentation {\nREALM_EXCLUDED_ATTRIBUTES.add(Constants.CLIENT_PROFILES);\n}\n+ private static final Logger LOG = Logger.getLogger(ModelToRepresentation.class);\npublic static void buildGroupPath(StringBuilder sb, GroupModel group) {\nif (group.getParent() != null) {\n@@ -554,6 +558,25 @@ public class ModelToRepresentation {\nreturn rep;\n}\n+ /**\n+ * Handles exceptions that occur when transforming the model to a representation and will remove\n+ * all null objects from the stream.\n+ *\n+ * Entities that have been removed from the store or where a lazy loading exception occurs will not show up\n+ * in the output stream.\n+ */\n+ public static <M, R> Stream<R> filterValidRepresentations(Stream<M> models, Function<M, R> transformer) {\n+ return models.map(m -> {\n+ try {\n+ return transformer.apply(m);\n+ } catch (ModelIllegalStateException e) {\n+ LOG.warn(\"unable to retrieve model information, skipping entity\", e);\n+ return null;\n+ }\n+ })\n+ .filter(Objects::nonNull);\n+ }\n+\npublic static CredentialRepresentation toRepresentation(UserCredentialModel cred) {\nCredentialRepresentation rep = new CredentialRepresentation();\nrep.setType(CredentialRepresentation.SECRET);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server-spi/src/main/java/org/keycloak/models/ModelIllegalStateException.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.keycloak.models;\n+\n+import java.util.function.Function;\n+import java.util.stream.Stream;\n+\n+/**\n+ * Thrown when data can't be retrieved for the model.\n+ *\n+ * This occurs when an entity has been removed or updated in the meantime. This might wrap an optimistic lock exception\n+ * depending on the store.\n+ *\n+ * Callers might use this exception to filter out entities that are in an illegal state, see\n+ * <code>org.keycloak.models.utils.ModelToRepresentation#toRepresentation(Stream, Function)</code>\n+ *\n+ * @author <a href=\"mailto:[email protected]\">Alexander Schwartz</a>\n+ */\n+public class ModelIllegalStateException extends ModelException {\n+\n+ public ModelIllegalStateException() {\n+ }\n+\n+ public ModelIllegalStateException(String message) {\n+ super(message);\n+ }\n+\n+ public ModelIllegalStateException(String message, Throwable cause) {\n+ super(message, cause);\n+ }\n+\n+ public ModelIllegalStateException(Throwable cause) {\n+ super(cause);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/exportimport/util/ExportUtils.java", "new_path": "services/src/main/java/org/keycloak/exportimport/util/ExportUtils.java", "diff": "package org.keycloak.exportimport.util;\n-import static org.keycloak.models.utils.ModelToRepresentation.toRepresentation;\n-\n-import java.io.IOException;\n-import java.io.OutputStream;\n-import java.util.ArrayList;\n-import java.util.Collection;\n-import java.util.Collections;\n-import java.util.HashMap;\n-import java.util.HashSet;\n-import java.util.LinkedList;\n-import java.util.List;\n-import java.util.Map;\n-import java.util.Set;\n-import java.util.stream.Collectors;\n-import java.util.stream.Stream;\n-\n+import com.fasterxml.jackson.core.JsonEncoding;\n+import com.fasterxml.jackson.core.JsonFactory;\n+import com.fasterxml.jackson.core.JsonGenerator;\n+import com.fasterxml.jackson.databind.ObjectMapper;\n+import com.fasterxml.jackson.databind.SerializationFeature;\nimport org.keycloak.authorization.AuthorizationProvider;\nimport org.keycloak.authorization.AuthorizationProviderFactory;\nimport org.keycloak.authorization.model.Policy;\n@@ -71,11 +60,20 @@ import org.keycloak.representations.idm.authorization.ResourceServerRepresentati\nimport org.keycloak.representations.idm.authorization.ScopeRepresentation;\nimport org.keycloak.util.JsonSerialization;\n-import com.fasterxml.jackson.core.JsonEncoding;\n-import com.fasterxml.jackson.core.JsonFactory;\n-import com.fasterxml.jackson.core.JsonGenerator;\n-import com.fasterxml.jackson.databind.ObjectMapper;\n-import com.fasterxml.jackson.databind.SerializationFeature;\n+import java.io.IOException;\n+import java.io.OutputStream;\n+import java.util.ArrayList;\n+import java.util.Collection;\n+import java.util.HashMap;\n+import java.util.HashSet;\n+import java.util.LinkedList;\n+import java.util.List;\n+import java.util.Map;\n+import java.util.Set;\n+import java.util.stream.Collectors;\n+import java.util.stream.Stream;\n+\n+import static org.keycloak.models.utils.ModelToRepresentation.toRepresentation;\n/**\n* @author <a href=\"mailto:[email protected]\">Marek Posolda</a>\n@@ -103,15 +101,17 @@ public class ExportUtils {\n.map(ClientScopeModel::getName).collect(Collectors.toList()));\n// Clients\n- List<ClientModel> clients = Collections.emptyList();\n+ List<ClientModel> clients = new LinkedList<>();\nif (options.isClientsIncluded()) {\n- clients = realm.getClientsStream()\n- .filter(c -> { try { c.getClientId(); return true; } catch (Exception ex) { return false; } } )\n- .collect(Collectors.toList());\n- List<ClientRepresentation> clientReps = clients.stream()\n- .map(app -> exportClient(session, app))\n- .collect(Collectors.toList());\n+ // we iterate over all clients in the stream.\n+ // only those client models that can be translated into a valid client representation will be added to the client list\n+ // that is later used to retrieve related information about groups and roles\n+ List<ClientRepresentation> clientReps = ModelToRepresentation.filterValidRepresentations(realm.getClientsStream(), app -> {\n+ ClientRepresentation clientRepresentation = exportClient(session, app);\n+ clients.add(app);\n+ return clientRepresentation;\n+ }).collect(Collectors.toList());\nrep.setClients(clientReps);\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/managers/ResourceAdminManager.java", "new_path": "services/src/main/java/org/keycloak/services/managers/ResourceAdminManager.java", "diff": "@@ -33,6 +33,7 @@ import org.keycloak.constants.AdapterConstants;\nimport org.keycloak.models.AuthenticatedClientSessionModel;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.KeycloakSession;\n+import org.keycloak.models.ModelIllegalStateException;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.protocol.LoginProtocol;\n@@ -241,15 +242,18 @@ public class ResourceAdminManager {\npublic GlobalRequestResult logoutAll(RealmModel realm) {\nrealm.setNotBefore(Time.currentTime());\n- Stream<ClientModel> resources = realm.getClientsStream()\n- .filter(c -> { try { c.getClientId(); return true; } catch (Exception ex) { return false; } } );\nGlobalRequestResult finalResult = new GlobalRequestResult();\nAtomicInteger counter = new AtomicInteger(0);\n- resources.forEach(r -> {\n+ realm.getClientsStream().forEach(c -> {\n+ try {\ncounter.getAndIncrement();\n- GlobalRequestResult currentResult = logoutClient(realm, r, realm.getNotBefore());\n+ GlobalRequestResult currentResult = logoutClient(realm, c, realm.getNotBefore());\nfinalResult.addAll(currentResult);\n+ } catch (ModelIllegalStateException ex) {\n+ // currently, GlobalRequestResult doesn't allow for information about clients that we were unable to retrieve.\n+ logger.warn(\"unable to retrieve client information for logout, skipping resource\", ex);\n+ }\n});\nlogger.debugv(\"logging out {0} resources \", counter);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/admin/ClientsResource.java", "new_path": "services/src/main/java/org/keycloak/services/resources/admin/ClientsResource.java", "diff": "@@ -57,7 +57,6 @@ import javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport java.util.Map;\n-import java.util.Objects;\nimport java.util.stream.Stream;\nimport static java.lang.Boolean.TRUE;\n@@ -87,9 +86,11 @@ public class ClientsResource {\n}\n/**\n- * Get clients belonging to the realm\n+ * Get clients belonging to the realm.\n*\n- * Returns a list of clients belonging to the realm\n+ * If a client can't be retrieved from the storage due to a problem with the underlying storage,\n+ * it is silently removed from the returned list.\n+ * This ensures that concurrent modifications to the list don't prevent callers from retrieving this list.\n*\n* @param clientId filter by clientId\n* @param viewableOnly filter clients that cannot be viewed in full by admin\n@@ -131,9 +132,8 @@ public class ClientsResource {\n}\n}\n- Stream<ClientRepresentation> s = clientModels\n- .filter(c -> { try { c.getClientId(); return true; } catch (Exception ex) { return false; } } )\n- .map(c -> {\n+ Stream<ClientRepresentation> s = ModelToRepresentation.filterValidRepresentations(clientModels,\n+ c -> {\nClientRepresentation representation = null;\nif (canView || auth.clients().canView(c)) {\nrepresentation = ModelToRepresentation.toRepresentation(c, session);\n@@ -146,8 +146,7 @@ public class ClientsResource {\n}\nreturn representation;\n- })\n- .filter(Objects::nonNull);\n+ });\nif (!canView) {\ns = paginatedStream(s, firstResult, maxResults);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Added ModelIllegalStateException to handle lazy loading exception. Closes #9645
339,425
28.01.2022 13:30:01
-3,600
dc814b85c77ef7a1b2f164441536ef77e1098974
Pass the UserId to the function that runs the inner function in the server as it was losing its value when defined globally for Wildfly and Quarkus
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/rar/AbstractRARParserTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/rar/AbstractRARParserTest.java", "diff": "@@ -88,7 +88,7 @@ public abstract class AbstractRARParserTest extends AbstractTestRealmKeycloakTes\n* @return the {@link AuthorizationRequestContextHolder} local testsuite representation of the Authorization Request Context\n* with all the parsed authorization_detail objects.\n*/\n- protected AuthorizationRequestContextHolder fetchAuthorizationRequestContextHolder() {\n+ protected AuthorizationRequestContextHolder fetchAuthorizationRequestContextHolder(String userId) {\nAuthorizationRequestContextHolder authorizationRequestContextHolder = testingClient.server(\"test\").fetch(session -> {\nfinal RealmModel realm = session.realms().getRealmByName(\"test\");\nfinal UserModel user = session.users().getUserById(realm, userId);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/rar/DynamicScopesRARParseTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/rar/DynamicScopesRARParseTest.java", "diff": "@@ -46,7 +46,6 @@ import static org.junit.Assert.assertEquals;\npublic class DynamicScopesRARParseTest extends AbstractRARParserTest {\n@Test\n- @Ignore(\"ignored until we figure out why it fails on Quarkus and Wildfly\")\npublic void generatedAuthorizationRequestsShouldMatchDefaultScopes() {\nClientResource testApp = ApiUtil.findClientByClientId(testRealm(), \"test-app\");\nList<ClientScopeRepresentation> defScopes = testApp.getDefaultClientScopes();\n@@ -56,7 +55,7 @@ public class DynamicScopesRARParseTest extends AbstractRARParserTest {\nevents.expectLogin()\n.user(userId)\n.assertEvent();\n- AuthorizationRequestContextHolder contextHolder = fetchAuthorizationRequestContextHolder();\n+ AuthorizationRequestContextHolder contextHolder = fetchAuthorizationRequestContextHolder(userId);\nList<AuthorizationRequestContextHolder.AuthorizationRequestHolder> authorizationRequestHolders = contextHolder.getAuthorizationRequestHolders().stream()\n.filter(authorizationRequestHolder -> authorizationRequestHolder.getSource().equals(AuthorizationRequestSource.SCOPE))\n.collect(Collectors.toList());\n@@ -73,7 +72,6 @@ public class DynamicScopesRARParseTest extends AbstractRARParserTest {\n}\n@Test\n- @Ignore(\"ignored until we figure out why it fails on Quarkus and Wildfly\")\npublic void generatedAuthorizationRequestsShouldMatchRequestedAndDefaultScopes() {\nResponse response = createScope(\"static-scope\", false);\nString scopeId = ApiUtil.getCreatedId(response);\n@@ -93,7 +91,7 @@ public class DynamicScopesRARParseTest extends AbstractRARParserTest {\n.user(userId)\n.assertEvent();\n- AuthorizationRequestContextHolder contextHolder = fetchAuthorizationRequestContextHolder();\n+ AuthorizationRequestContextHolder contextHolder = fetchAuthorizationRequestContextHolder(userId);\nList<AuthorizationRequestContextHolder.AuthorizationRequestHolder> authorizationRequestHolders = contextHolder.getAuthorizationRequestHolders().stream()\n.filter(authorizationRequestHolder -> authorizationRequestHolder.getSource().equals(AuthorizationRequestSource.SCOPE))\n.collect(Collectors.toList());\n@@ -112,7 +110,6 @@ public class DynamicScopesRARParseTest extends AbstractRARParserTest {\n}\n@Test\n- @Ignore(\"ignored until we figure out why it fails on Quarkus and Wildfly\")\npublic void generatedAuthorizationRequestsShouldMatchRequestedDynamicAndDefaultScopes() {\nResponse response = createScope(\"dynamic-scope\", true);\nString scopeId = ApiUtil.getCreatedId(response);\n@@ -132,7 +129,7 @@ public class DynamicScopesRARParseTest extends AbstractRARParserTest {\n.user(userId)\n.assertEvent();\n- AuthorizationRequestContextHolder contextHolder = fetchAuthorizationRequestContextHolder();\n+ AuthorizationRequestContextHolder contextHolder = fetchAuthorizationRequestContextHolder(userId);\nList<AuthorizationRequestContextHolder.AuthorizationRequestHolder> authorizationRequestHolders = contextHolder.getAuthorizationRequestHolders().stream()\n.filter(authorizationRequestHolder -> authorizationRequestHolder.getSource().equals(AuthorizationRequestSource.SCOPE))\n.collect(Collectors.toList());\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Pass the UserId to the function that runs the inner function in the server as it was losing its value when defined globally for Wildfly and Quarkus
339,618
28.01.2022 16:02:51
-3,600
5a1f4b888928bee88de4e7733c0b80934f431c55
Quarkus update to 2.7.0.Final Minor and micro dependency updates, some relocations (e.g. vault, ZipUtils), so some changes were needed to make this work. Closes
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<packaging>pom</packaging>\n<properties>\n- <quarkus.version>2.5.4.Final</quarkus.version>\n+ <quarkus.version>2.7.0.Final</quarkus.version>\n<!--\nPerforming a Wildfly upgrade? Run the:\n" }, { "change_type": "MODIFY", "old_path": "quarkus/deployment/pom.xml", "new_path": "quarkus/deployment/pom.xml", "diff": "<artifactId>quarkus-smallrye-metrics-deployment</artifactId>\n</dependency>\n<dependency>\n- <groupId>io.quarkus</groupId>\n+ <groupId>io.quarkiverse.vault</groupId>\n<artifactId>quarkus-vault-deployment</artifactId>\n+ <version>1.0.1</version>\n</dependency>\n<dependency>\n<groupId>io.quarkus</groupId>\n" }, { "change_type": "MODIFY", "old_path": "quarkus/pom.xml", "new_path": "quarkus/pom.xml", "diff": "See https://github.com/quarkusio/quarkus/blob/<versionTag>/bom/application/pom.xml\nfor reference\n-->\n- <resteasy.version>4.7.3.Final</resteasy.version>\n- <jackson.version>2.12.5</jackson.version>\n+ <resteasy.version>4.7.5.Final</resteasy.version>\n+ <jackson.version>2.13.1</jackson.version>\n<jackson.databind.version>${jackson.version}</jackson.databind.version>\n- <hibernate.core.version>5.6.1.Final</hibernate.core.version>\n- <mysql.driver.version>8.0.27</mysql.driver.version>\n+ <hibernate.core.version>5.6.5.Final</hibernate.core.version>\n+ <mysql.driver.version>8.0.28</mysql.driver.version>\n<postgresql.version>42.3.1</postgresql.version>\n<microprofile-metrics-api.version>3.0</microprofile-metrics-api.version>\n<wildfly.common.version>1.5.4.Final-format-001</wildfly.common.version>\n- <infinispan.version>13.0.0.Final</infinispan.version>\n-\n+ <infinispan.version>13.0.5.Final</infinispan.version>\n<!--\nJava EE dependencies. Not available from JDK 11+.\nThe dependencies and their versions are the same used by Wildfly distribution.\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/pom.xml", "new_path": "quarkus/runtime/pom.xml", "diff": "<artifactId>quarkus-smallrye-metrics</artifactId>\n</dependency>\n<dependency>\n- <groupId>io.quarkus</groupId>\n+ <groupId>io.quarkiverse.vault</groupId>\n<artifactId>quarkus-vault</artifactId>\n+ <version>1.0.1</version>\n</dependency>\n<!-- CLI -->\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/vault/QuarkusVaultProvider.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/vault/QuarkusVaultProvider.java", "diff": "@@ -24,6 +24,7 @@ import java.nio.charset.StandardCharsets;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n+\nimport org.keycloak.vault.AbstractVaultProvider;\nimport org.keycloak.vault.VaultKeyResolver;\nimport org.keycloak.vault.VaultRawSecret;\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/resources/META-INF/services/quarkus.properties", "new_path": "quarkus/runtime/src/main/resources/META-INF/services/quarkus.properties", "diff": "quarkus.log.level = INFO\nquarkus.log.category.\"org.jboss.resteasy.resteasy_jaxrs.i18n\".level=WARN\nquarkus.log.category.\"org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup\".level=WARN\n+\n+#jndi needed for LDAP lookups\n+quarkus.naming.enable-jndi=true\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/main/java/org/keycloak/it/utils/RawKeycloakDistribution.java", "new_path": "quarkus/tests/integration/src/main/java/org/keycloak/it/utils/RawKeycloakDistribution.java", "diff": "@@ -45,9 +45,10 @@ import javax.net.ssl.SSLSession;\nimport javax.net.ssl.SSLSocketFactory;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.X509TrustManager;\n+\n+import io.quarkus.fs.util.ZipUtils;\nimport org.apache.commons.io.FileUtils;\n-import io.quarkus.bootstrap.util.ZipUtils;\nimport org.keycloak.common.Version;\npublic final class RawKeycloakDistribution implements KeycloakDistribution {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/servers/auth-server/quarkus/src/main/content/conf/quarkus.properties", "diff": "+quarkus.naming.enable-jndi=true\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Quarkus update to 2.7.0.Final Minor and micro dependency updates, some relocations (e.g. vault, ZipUtils), so some changes were needed to make this work. Closes #9872
339,460
31.01.2022 21:15:32
-3,600
99213ab04217e0606be549a521608aea1d854191
hardcoded string replaced with localization
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak.v2/account/src/app/content/account-page/AccountPage.tsx", "new_path": "themes/src/main/resources/theme/keycloak.v2/account/src/app/content/account-page/AccountPage.tsx", "diff": "@@ -250,7 +250,7 @@ export class AccountPage extends React.Component<AccountPageProps, AccountPageSt\n{ this.isDeleteAccountAllowed &&\n<div id=\"delete-account\" style={{marginTop:\"30px\"}}>\n- <Expandable toggleText=\"Delete Account\">\n+ <Expandable toggleText={Msg.localize('deleteAccount')}>\n<Grid gutter={\"sm\"}>\n<GridItem span={6}>\n<p>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
hardcoded string replaced with localization (#9543) Co-authored-by: Andreas Ruehl <[email protected]>
339,618
01.02.2022 14:08:44
-3,600
829e2a9a3e6bf477123b92c0a5cf47da1f066cda
Change test order Closes
[ { "change_type": "MODIFY", "old_path": ".github/workflows/ci.yml", "new_path": ".github/workflows/ci.yml", "diff": "@@ -412,12 +412,6 @@ jobs:\n- name: Prepare the local distribution archives\nrun: mvn clean install -DskipTests -Pdistribution\n- - name: Run Quarkus Tests in Docker\n- run: |\n- mvn clean install -nsu -B -f quarkus/tests/pom.xml -Dkc.quarkus.tests.dist=docker | misc/log/trimmer.sh\n- TEST_RESULT=${PIPESTATUS[0]}\n- exit $TEST_RESULT\n-\n- name: Run Quarkus Integration Tests\nrun: |\nmvn clean install -nsu -B -f quarkus/tests/pom.xml | misc/log/trimmer.sh\n@@ -432,6 +426,12 @@ jobs:\nfind . -path '*/target/surefire-reports/*.xml' | zip -q reports-quarkus-tests.zip -@\nexit $TEST_RESULT\n+ - name: Run Quarkus Tests in Docker\n+ run: |\n+ mvn clean install -nsu -B -f quarkus/tests/pom.xml -Dkc.quarkus.tests.dist=docker | misc/log/trimmer.sh\n+ TEST_RESULT=${PIPESTATUS[0]}\n+ exit $TEST_RESULT\n+\n- name: Quarkus test reports\nuses: actions/upload-artifact@v2\nif: failure()\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Change test order (#9911) Closes #9910
339,410
24.01.2022 14:59:34
-3,600
9d46b45a9cf963fdcbdfe43bd7e2e6d58958f41b
Ensure that parent's version ID is incremented when an attribute changes. This is necessary to allow the optimistic locking functionality to work as expected when changing only attributes on an entity. Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaChildEntity.java", "diff": "+/*\n+ * Copyright 2022. Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.keycloak.models.map.storage.jpa;\n+\n+/**\n+ * Interface for all child entities for JPA map storage.\n+ */\n+public interface JpaChildEntity<R> {\n+\n+ /**\n+ * Parent entity that should get its optimistic locking version updated upon changes in the child\n+ */\n+ R getParent();\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaChildEntityListener.java", "diff": "+/*\n+ * Copyright 2022. Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.models.map.storage.jpa;\n+\n+import org.hibernate.HibernateException;\n+import org.hibernate.Session;\n+import org.hibernate.event.spi.PreDeleteEvent;\n+import org.hibernate.event.spi.PreDeleteEventListener;\n+import org.hibernate.event.spi.PreInsertEvent;\n+import org.hibernate.event.spi.PreInsertEventListener;\n+import org.hibernate.event.spi.PreUpdateEvent;\n+import org.hibernate.event.spi.PreUpdateEventListener;\n+\n+import javax.persistence.LockModeType;\n+\n+/**\n+ * Listen on changes on child entities and forces an optimistic locking increment on the topmost parent.\n+ *\n+ * This support a multiple level parent-child relationship, where only the upmost parent is locked.\n+ */\n+public class JpaChildEntityListener implements PreInsertEventListener, PreDeleteEventListener, PreUpdateEventListener {\n+\n+ public static final JpaChildEntityListener INSTANCE = new JpaChildEntityListener();\n+\n+ /**\n+ * Check if the entity is a child with a parent and force optimistic locking increment on the upmost parent.\n+ */\n+ public void checkRoot(Session session, Object entity) throws HibernateException {\n+ if(entity instanceof JpaChildEntity) {\n+ Object root = entity;\n+ while (root instanceof JpaChildEntity) {\n+ root = ((JpaChildEntity<?>) entity).getParent();\n+ }\n+ session.lock(root, LockModeType.OPTIMISTIC_FORCE_INCREMENT);\n+ }\n+ }\n+\n+ @Override\n+ public boolean onPreInsert(PreInsertEvent event) {\n+ checkRoot(event.getSession(), event.getEntity());\n+ return false;\n+ }\n+\n+ @Override\n+ public boolean onPreDelete(PreDeleteEvent event) {\n+ checkRoot(event.getSession(), event.getEntity());\n+ return false;\n+ }\n+\n+ @Override\n+ public boolean onPreUpdate(PreUpdateEvent event) {\n+ checkRoot(event.getSession(), event.getEntity());\n+ return false;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaMapStorageProviderFactory.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaMapStorageProviderFactory.java", "diff": "@@ -20,6 +20,7 @@ import java.sql.Connection;\nimport java.sql.DatabaseMetaData;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n+import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n@@ -30,7 +31,14 @@ import javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.sql.DataSource;\n+\n+import org.hibernate.boot.Metadata;\nimport org.hibernate.cfg.AvailableSettings;\n+import org.hibernate.engine.spi.SessionFactoryImplementor;\n+import org.hibernate.event.service.spi.EventListenerRegistry;\n+import org.hibernate.event.spi.EventType;\n+import org.hibernate.jpa.boot.spi.IntegratorProvider;\n+import org.hibernate.service.spi.SessionFactoryServiceRegistry;\nimport org.jboss.logging.Logger;\nimport org.keycloak.Config;\nimport org.keycloak.common.Profile;\n@@ -166,6 +174,31 @@ public class JpaMapStorageProviderFactory implements\nproperties.put(\"hibernate.format_sql\", config.getBoolean(\"formatSql\", true));\nproperties.put(\"hibernate.dialect\", config.get(\"driverDialect\"));\n+ properties.put(\n+ \"hibernate.integrator_provider\",\n+ (IntegratorProvider) () -> Collections.singletonList(\n+ new org.hibernate.integrator.spi.Integrator() {\n+\n+ @Override\n+ public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactoryImplementor,\n+ SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {\n+ final EventListenerRegistry eventListenerRegistry =\n+ sessionFactoryServiceRegistry.getService( EventListenerRegistry.class );\n+\n+ eventListenerRegistry.appendListeners(EventType.PRE_INSERT, JpaChildEntityListener.INSTANCE);\n+ eventListenerRegistry.appendListeners(EventType.PRE_UPDATE, JpaChildEntityListener.INSTANCE);\n+ eventListenerRegistry.appendListeners(EventType.PRE_DELETE, JpaChildEntityListener.INSTANCE);\n+ }\n+\n+ @Override\n+ public void disintegrate(SessionFactoryImplementor sessionFactoryImplementor,\n+ SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {\n+\n+ }\n+ }\n+ )\n+ );\n+\nInteger isolation = config.getInt(\"isolation\");\nif (isolation != null) {\nif (isolation < Connection.TRANSACTION_REPEATABLE_READ) {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "diff": "@@ -28,10 +28,11 @@ import javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\nimport org.hibernate.annotations.Nationalized;\n+import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n@Entity\n@Table(name = \"client_attribute\")\n-public class JpaClientAttributeEntity implements Serializable {\n+public class JpaClientAttributeEntity implements JpaChildEntity<JpaClientEntity>, Serializable {\n@Id\n@Column\n@@ -100,4 +101,9 @@ public class JpaClientAttributeEntity implements Serializable {\nObjects.equals(getName(), that.getName()) &&\nObjects.equals(getValue(), that.getValue());\n}\n+\n+ @Override\n+ public JpaClientEntity getParent() {\n+ return getClient();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "diff": "@@ -587,7 +587,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\nJpaClientAttributeEntity attr = iterator.next();\nif (Objects.equals(attr.getName(), name)) {\niterator.remove();\n- attr.setClient(null);\n}\n}\n}\n@@ -625,9 +624,7 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\npublic void setAttributes(Map<String, List<String>> attributes) {\ncheckEntityVersionForUpdate();\nfor (Iterator<JpaClientAttributeEntity> iterator = this.attributes.iterator(); iterator.hasNext();) {\n- JpaClientAttributeEntity attr = iterator.next();\niterator.remove();\n- attr.setClient(null);\n}\nif (attributes != null) {\nfor (Map.Entry<String, List<String>> attrEntry : attributes.entrySet()) {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "diff": "@@ -28,10 +28,12 @@ import javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\nimport org.hibernate.annotations.Nationalized;\n+import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n+import org.keycloak.models.map.storage.jpa.client.entity.JpaClientEntity;\n@Entity\n@Table(name = \"role_attribute\")\n-public class JpaRoleAttributeEntity implements Serializable {\n+public class JpaRoleAttributeEntity implements JpaChildEntity<JpaRoleEntity>, Serializable {\n@Id\n@Column\n@@ -100,4 +102,9 @@ public class JpaRoleAttributeEntity implements Serializable {\nObjects.equals(getName(), that.getName()) &&\nObjects.equals(getValue(), that.getValue());\n}\n+\n+ @Override\n+ public JpaRoleEntity getParent() {\n+ return role;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "diff": "@@ -257,9 +257,7 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\npublic void setAttributes(Map<String, List<String>> attributes) {\ncheckEntityVersionForUpdate();\nfor (Iterator<JpaRoleAttributeEntity> iterator = this.attributes.iterator(); iterator.hasNext();) {\n- JpaRoleAttributeEntity attr = iterator.next();\niterator.remove();\n- attr.setRole(null);\n}\nif (attributes != null) {\nfor (Map.Entry<String, List<String>> entry : attributes.entrySet()) {\n@@ -285,7 +283,6 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\nJpaRoleAttributeEntity attr = iterator.next();\nif (Objects.equals(attr.getName(), name)) {\niterator.remove();\n- attr.setRole(null);\n}\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Ensure that parent's version ID is incremented when an attribute changes. This is necessary to allow the optimistic locking functionality to work as expected when changing only attributes on an entity. Closes #9874
339,181
02.02.2022 02:43:35
18,000
4dd27e43d181df24e023f2d9ead94262e130fec1
9847 Addressing comments from Dominik
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/containers.adoc", "new_path": "docs/guides/src/main/server/containers.adoc", "diff": "<#import \"/templates/links.adoc\" as links>\n<@tmpl.guide\n-title=\"Running in a container\"\n+title=\"Running Keycloak in a container\"\nsummary=\"Learn how to run Keycloak from a container image\"\nincludedOptions=\"db db-url db-username db-password features hostname https-key-store-file https-key-store-password metrics-enabled\">\n-Keycloak is handling containerized environments like Kubernetes or OpenShift as first-class-citizens. In this guide you'll learn how to run and optimize the Keycloak container image to have the best experience running a Keycloak container.\n+Keycloak handles containerized environments such as Kubernetes or OpenShift as first-class citizens. This guide describes how to optimize and run the Keycloak container image to provide the best experience running a Keycloak container.\n-== Create an optimized container image\n-To get the best startup experience for your Keycloak container, we recommend building an optimized container image by running the `build` step explicitly before starting:\n+== Creating an optimized container image\n+For the best start up of your Keycloak container, build an optimized container image by running the `build` step before starting.\n-=== Build your optimized Keycloak docker image\n-The `Dockerfile` below creates a pre-configured Keycloak image which enables the metrics endpoint, the token exchange feature and uses a postgres database.\n+=== Building your optimized Keycloak docker image\n+The following `Dockerfile` creates a pre-configured Keycloak image that enables the metrics endpoint, enables the token exchange feature, and uses a PostgreSQL database.\n.Dockerfile:\n[source, dockerfile]\n@@ -40,35 +40,42 @@ ENV KC_DB_PASSWORD=<DBPASSWORD>\nENV KC_HOSTNAME=localhost:8443\nENTRYPOINT [\"/opt/keycloak/bin/kc.sh\", \"start\"]\n----\n-In the first stage of this multi-staged build, we're creating the optimized image using the `build` command to apply the build options. From the `builder`, we're copying the files generated by the `build` process into a new image. In this runner image, we apply the specific run configuration, containing e.g. a keystore, the environment-specific hostname configuration and database configuration. Then this image gets started in production mode by using the `start` command in the entrypoint.\n+The build process includes multiple stages:\n-Note that this example uses a multi-staged build to explicitly showcase the build and run steps. It could also be run as a single-staged docker build.\n+* The `build` command applies options that create an optimized image.\n+* The files generated by the `build` process are copied into a new image.\n+* In this runner image, the specific run configuration is applied. That configuration contains a keystore, the environment-specific hostname configuration, and database configuration.\n+* In the entrypoint, the `start` command starts the image in production mode.\n+\n+This example uses a multi-staged build to demonstrate the build and run steps. However, you can also run this process as a single-staged docker build.\n=== Building the docker image\n-To build the actual docker image, run the following command form the Directory containing your Dockerfile:\n+To build the actual docker image, run the following command from the directory containing your Dockerfile:\n+\n[source,bash]\n----\npodman|docker build . -t prebuilt_keycloak\n----\n-=== Start the optimized Keycloak docker image:\n+=== Starting the optimized Keycloak docker image\nTo start the image, run:\n[source, bash]\n----\npodman|docker run --name optimized_keycloak -p 8443:8443 prebuilt_keycloak\n----\n-Keycloak starts up in production mode, using only secured HTTPS communication, and is available on `https://localhost:8443`.\n-You'll notice that the startup log contains the following line:\n+Keycloak starts in production mode, using only secured HTTPS communication, and is available on `https://localhost:8443`.\n+Notice that the startup log contains the following line:\n[source, bash]\n----\nINFO [org.key.com.Profile] (main) Preview feature enabled: token_exchange\n----\n-This shows the desired feature is enabled.\n+This message shows the desired feature is enabled.\n-Opening up `https://localhost:8443/metrics` leads to a page containing operational metrics which could be used by your monitoring solution.\n+Opening up `https://localhost:8443/metrics` leads to a page containing operational metrics that could be used by your monitoring solution.\n-== Try Keycloak out in development mode\n-The easiest way to try out Keycloak from a container for development or testing purposes is using the Development mode by using the `start-dev` command:\n+== Trying Keycloak in development mode\n+The easiest way to try Keycloak from a container for development or testing purposes is to use the Development mode.\n+You use the `start-dev` command:\n[source,bash]\n----\n@@ -78,14 +85,16 @@ podman|docker run --name keycloak_test -p 8080:8080 \\\nstart-dev\n----\n-Invoking this command will spin up the Keycloak server in development mode.\n+Invoking this command starts the Keycloak server in development mode.\n-Keep in mind that this mode is by no means meant to be used in production environments, as it has insecure defaults. For more information about running Keycloak in production, see _todo_link_to_running_in_production_guide_.\n+This mode should be strictly avoided in production environments because it has insecure defaults.\n+For more information about running Keycloak in production, see _todo_link_to_running_in_production_guide_.\n== Use auto-build to run a standard keycloak container\n-Following concepts such as immutable infrastructure, containers need to be re-provisioned fairly often. In these environments, you want to have containers which start up fast by using an optimized image as described above.\n-\n-However, when your environment is different, you may want to run a standard Keycloak image using the `--auto-build` flag like below:\n+In keeping with concepts such as immutable infrastructure, containers need to be re-provisioned routinely.\n+In these environments, you need containers that start fast, therefore you need to create an optimized image as described in the preceding section.\n+However, if your environment has different requirements, you can run a standard Keycloak image using the `--auto-build` flag.\n+For example:\n[source, bash]\n----\n@@ -99,8 +108,10 @@ podman|docker run --name keycloak_auto_build -p 8080:8080 \\\n--https-key-store-file=<file> --https-key-store-password=<password>\n----\n-Running the above will spin up a Keycloak server which detects and applies the build configuration first. In the example, it's `--db=postgres --features=token-exchange` to set the used database vendor to postgres and enable the token exchange feature.\n+Running this command starts a Keycloak server that detects and applies the build options first.\n+In the example, the line `--db=postgres --features=token-exchange` sets the database vendor to PostgreSQL and enables the token exchange feature.\n-Keycloak will then start up and apply the configuration for the specific environment. This approach results in a significantly bigger startup time, and an image that is mutable, and is therefor not the best practice.\n+Keycloak then starts up and applies the configuration for the specific environment.\n+This approach significantly increases startup time and creates an image that is mutable, which is not the best practice.\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
9847 Addressing comments from Dominik (#9883)
339,181
02.02.2022 02:46:14
18,000
bd0fda8643e1f988ab230fdd75daa3d0b1547239
9921 fixing a typo. thanks, Dominik
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/features.adoc", "new_path": "docs/guides/src/main/server/features.adoc", "diff": "@@ -7,38 +7,38 @@ title=\"Enabling and disabling features\"\nsummary=\"Understand how to configure Keycloak to use optional features\"\nincludedOptions=\"features features-*\">\n-Keycloak has packed some functionality in features, some of them not enabled by default. These features include features that are in tech preview or deprecated features. In addition there are some features that are enabled by default, but can be disabled if you don't need them for your specific usage scenario.\n+Keycloak has packed some functionality in features, including some disabled features, such as Technology Preview and deprecated features. Other features are enabled by default, but you can disable them if they do not apply to your use of Keycloak.\n== Enabling features\n-Some supported features, and all preview features, are not enabled by default. To enable a feature use:\n+Some supported features, and all preview features, are disabled by default. To enable a feature, enter this command:\n<@kc.build parameters=\"--features=<name>[,<name>]\"/>\n-For example to enable `docker` and `token-exchange` use:\n+For example, to enable `docker` and `token-exchange`, enter this command:\n<@kc.build parameters=\"--features=docker,token-exchange\"/>\n-All preview features can be enabled with the special name `preview`:\n+To enable all preview features, enter this command:\n<@kc.build parameters=\"--features=preview\"/>\n== Disabling features\n-To disable a feature that is enabled by default use:\n+To disable a feature that is enabled by default, enter this command:\n<@kc.build parameters=\"--features-disabled=<name>[,<name>]\"/>\n-For example to disable `impersonation` use:\n+For example to disable `impersonation`, enter this command:\n<@kc.build parameters=\"--features-disabled=impersonation\"/>\n-It is also possible to disable all default features with:\n+You can disable all default features by entering this command:\n<@kc.build parameters=\"--features-disabled=default\"/>\n-This can be used in combination with `features` to explicitly set what features should be available. If a feature is\n-added both to the `features-disabled` list and the `features` list it will be enabled.\n+This command can be used in combination with `features` to explicitly set what features should be available.\n+If a feature is added both to the `features-disabled` list and the `features` list, it will be enabled.\n== Supported features\n@@ -48,20 +48,20 @@ The following list contains supported features that are enabled by default, and\n=== Disabled by default\n-The following list contains supported features that are not enabled by default, and can be enabled if needed.\n+The following list contains supported features that are disabled by default, and can be enabled if needed.\n<@showFeatures ctx.features.supportedDisabledByDefault/>\n== Preview features\n-Preview features are not enabled by default, and are not recommended for use in production. These features may change, or\n-even be removed, in a future release.\n+Preview features are disabled by default and are not recommended for use in production.\n+These features may change or be removed at a future release.\n<@showFeatures ctx.features.preview/>\n== Deprecated features\n-The following list contains deprecated features that will be removed in a future release. These features are not enabled by default.\n+The following list contains deprecated features that will be removed in a future release. These features are disabled by default.\n<@showFeatures ctx.features.deprecated/>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
9921 fixing a typo. thanks, Dominik (#9924)
339,181
02.02.2022 02:48:04
18,000
030163048016410215cbf4316b8e44e42927911e
9904 Editing the enable TLS guide
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/enabletls.adoc", "new_path": "docs/guides/src/main/server/enabletls.adoc", "diff": "<#import \"/templates/kc.adoc\" as kc>\n<@tmpl.guide\n-title=\"Configure TLS\"\n-summary=\"Learn how to configure Keycloak's https certificates for in- and outgoing requests as well as mTLS.\"\n+title=\"Configuring TLS\"\n+summary=\"Learn how to configure Keycloak's https certificates for ingoing and outgoing requests as well as mTLS.\"\nincludedOptions=\"https-* http-enabled\">\n-Transport Layer Security (short: TLS) is crucial to exchange data over a secured channel. For production environments, you should never expose Keycloak endpoints through HTTP, as sensitive data is at the core of what Keycloak exchanges with other applications. In this guide you will learn how to configure Keycloak to use HTTPS/TLS.\n+Transport Layer Security (short: TLS) is crucial to exchange data over a secured channel.\n+For production environments, you should never expose Keycloak endpoints through HTTP, as sensitive data is at the core of what Keycloak exchanges with other applications.\n+In this guide, you will learn how to configure Keycloak to use HTTPS/TLS.\n-== Configure TLS in Keycloak\n-Keycloak can be configured to load the needed certificate infrastructure using files in PEM format or from a Java KeyStore. When both alternatives are set up, the PEM files takes precedence over the Java KeyStores.\n+== Configuring TLS in Keycloak\n+Keycloak can be configured to load the required certificate infrastructure using files in PEM format or from a Java Keystore.\n+When both alternatives are configured, the PEM files takes precedence over the Java Keystores.\n=== Providing certificates in PEM format\n-When you use a pair of matching certificate / private key files in PEM format, configure Keycloak to use them by running:\n+When you use a pair of matching certificate and private key files in PEM format, you configure Keycloak to use them by running the following command:\n<@kc.start parameters=\"--https-certificate-file=/path/to/certfile.pem --https-certificate-key-file=/path/to/keyfile.pem\"/>\nKeycloak creates a keystore out of these files in memory and uses this keystore afterwards.\n-=== Providing a Java KeyStore\n-When no keystore file is configured explicitly, but `http.enabled` is set to false, Keycloak looks for a `conf/server.keystore` file by default.\n+=== Providing a Java Keystore\n+When no keystore file is explicitly configured, but `http.enabled` is set to false, Keycloak looks for a `conf/server.keystore` file.\n-As an alternative, you can use an existing keystore by running:\n+As an alternative, you can use an existing keystore by running the following command:\n<@kc.start parameters=\"--https-key-store-file=/path/to/existing-keystore-file\"/>\n-==== Setting the KeyStore password\n+==== Setting the Keystore password\nYou can set a secure password for your keystore using the `https.key-store.password` option:\n<@kc.start parameters=\"--https-key-store-password=<value>\"/>\n+\nIf no password is set, the default password `password` is used.\n-== Configure TLS protocols\n-By default, Keycloak does not enable deprecated TLS protocols. In situations where clients only support deprecated protocols, first consider upgrading the client, but as a temporary work-around you can enable deprecated protocols with:\n+== Configuring TLS protocols\n+By default, Keycloak does not enable deprecated TLS protocols.\n+If your client supports only deprecated protocols, consider upgrading the client.\n+However, as a temporary work-around, you can enable deprecated protocols by running the following command:\n<@kc.start parameters=\"--https-protocols=<protocol>[,<protocol>]\"/>\n-To also allow TLSv1.2, use for example `kc.sh start --https-protocols=TLSv1.3,TLSv1.2`.\n+To also allow TLSv1.2, use a command such as the following: `kc.sh start --https-protocols=TLSv1.3,TLSv1.2`.\n-== Switch the HTTPS port\n-Keycloak listens for HTTPS traffic on port `8443` by default. To change this port, use:\n+== Switching the HTTPS port\n+Keycloak listens for HTTPS traffic on port `8443`. To change this port, use the following command:\n<@kc.start parameters=\"--https-port=<port>\"/>\n== Using a truststore\n-Keycloak uses a truststore to store certificates to verify clients that are communicating with Keycloak, e.g. to use mutualTLS, certificate-bound tokens or X.509 authentication. This truststore is used for outgoing https requests as well as mTLS requests.\n+Keycloak uses a truststore to store certificates to verify clients that are communicating with Keycloak.\n+Examples of client requests are for using mutualTLS, certificate-bound tokens or X.509 authentication.\n+This truststore is used for outgoing https requests as well as mTLS requests.\n-You can configure the location of this truststore by running:\n+You can configure the location of this truststore by running the following command:\n<@kc.start parameters=\"--https-trust-store-file=/path/to/file\"/>\n=== Setting the truststore password\n@@ -52,6 +60,8 @@ You can set a secure password for your truststore using the `https.trust-store.p\nIf no password is set, the default password `password` is used.\n== Securing credentials\n-We recommend to not set any password in plaintext via the CLI or in `conf/keycloak.conf`, but instead using good practices such as using a vault / mounted secret. Please refer to the Vault Guide / Production deployment guide for more advice.\n+Avoid setting a password in plaintext by using the CLI or adding it to `conf/keycloak.conf` file.\n+Instead use good practices such as using a vault / mounted secret. For more detail, see the Vault Guide / Production deployment guide.\n+\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
9904 Editing the enable TLS guide (#9909)
339,465
02.02.2022 15:21:44
-3,600
d27635fb1b2cf6c411902357cd6fbad7498d102b
Fixing for token revocation checks only Closes
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authorization/util/Tokens.java", "new_path": "services/src/main/java/org/keycloak/authorization/util/Tokens.java", "diff": "package org.keycloak.authorization.util;\n-import org.keycloak.models.KeycloakContext;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.representations.AccessToken;\nimport org.keycloak.services.managers.AppAuthManager;\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "diff": "@@ -240,18 +240,13 @@ public class TokenManager {\ntry {\nTokenVerifier.createWithoutSignature(token)\n- .withChecks(NotBeforeCheck.forModel(client), TokenVerifier.IS_ACTIVE)\n+ .withChecks(NotBeforeCheck.forModel(client), TokenVerifier.IS_ACTIVE, new TokenRevocationCheck(session))\n.verify();\n} catch (VerificationException e) {\nlogger.debugf(\"JWT check failed: %s\", e.getMessage());\nreturn false;\n}\n- TokenRevocationStoreProvider revocationStore = session.getProvider(TokenRevocationStoreProvider.class);\n- if (revocationStore.isRevoked(token.getId())) {\n- return false;\n- }\n-\nboolean valid = false;\n// Tokens without sessions are considered valid. Signature check and revocation check are sufficient checks for them\n@@ -1346,6 +1341,24 @@ public class TokenManager {\n}\n}\n+ /**\n+ * Check if access token was revoked with OAuth revocation endpoint\n+ */\n+ public static class TokenRevocationCheck implements TokenVerifier.Predicate<AccessToken> {\n+\n+ private final KeycloakSession session;\n+\n+ public TokenRevocationCheck(KeycloakSession session) {\n+ this.session = session;\n+ }\n+\n+ @Override\n+ public boolean test(AccessToken token) {\n+ TokenRevocationStoreProvider revocationStore = session.getProvider(TokenRevocationStoreProvider.class);\n+ return !revocationStore.isRevoked(token.getId());\n+ }\n+ }\n+\npublic LogoutTokenValidationCode verifyLogoutToken(KeycloakSession session, RealmModel realm, String encodedLogoutToken) {\nOptional<LogoutToken> logoutTokenOptional = toLogoutToken(encodedLogoutToken);\nif (!logoutTokenOptional.isPresent()) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/UserInfoEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/UserInfoEndpoint.java", "diff": "@@ -174,7 +174,7 @@ public class UserInfoEndpoint {\ncors.allowedOrigins(session, clientModel);\nTokenVerifier.createWithoutSignature(token)\n- .withChecks(NotBeforeCheck.forModel(clientModel))\n+ .withChecks(NotBeforeCheck.forModel(clientModel), new TokenManager.TokenRevocationCheck(session))\n.verify();\n} catch (VerificationException e) {\nif (clientModel == null) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java", "new_path": "services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java", "diff": "@@ -1395,6 +1395,11 @@ public class AuthenticationManager {\nverifier.audience(checkAudience);\n}\n+ // Check token revocation in case of access token\n+ if (checkTokenType) {\n+ verifier.withChecks(new TokenManager.TokenRevocationCheck(session));\n+ }\n+\nString kid = verifier.getHeader().getKeyId();\nString algorithm = verifier.getHeader().getAlgorithm().name();\n@@ -1432,7 +1437,11 @@ public class AuthenticationManager {\nUserSessionModel offlineUserSession = session.sessions().getOfflineUserSession(realm, token.getSessionState());\nif (isOfflineSessionValid(realm, offlineUserSession)) {\nuser = offlineUserSession.getUser();\n- return new AuthResult(user, offlineUserSession, token);\n+ ClientModel client = realm.getClientByClientId(token.getIssuedFor());\n+ if (!isClientValid(offlineUserSession, client, token)) {\n+ return null;\n+ }\n+ return new AuthResult(user, offlineUserSession, token, client);\n}\n}\n@@ -1443,13 +1452,45 @@ public class AuthenticationManager {\nsession.setAttribute(\"state_checker\", token.getOtherClaims().get(\"state_checker\"));\n- return new AuthResult(user, userSession, token);\n+ ClientModel client;\n+ if (isCookie) {\n+ client = null;\n+ } else {\n+ client = realm.getClientByClientId(token.getIssuedFor());\n+ if (!isClientValid(userSession, client, token)) {\n+ return null;\n+ }\n+ }\n+ return new AuthResult(user, userSession, token, client);\n} catch (VerificationException e) {\nlogger.debugf(\"Failed to verify identity token: %s\", e.getMessage());\n}\nreturn null;\n}\n+ // Verify client and whether clientSession exists\n+ private static boolean isClientValid(UserSessionModel userSession, ClientModel client, AccessToken token) {\n+ if (client == null || !client.isEnabled()) {\n+ logger.debugf(\"Identity token issued for unknown or disabled client '%s'\", token.getIssuedFor());\n+ return false;\n+ }\n+\n+ if (token.getIssuedAt() < client.getNotBefore()) {\n+ logger.debug(\"Client notBefore newer than token\");\n+ return false;\n+ }\n+\n+ // User session may not exists for example during client credentials auth\n+ if (userSession == null) return true;\n+\n+ AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());\n+ if (clientSession == null) {\n+ logger.debugf(\"Client session for client '%s' not present in user session '%s'\", client.getClientId(), userSession.getId());\n+ return false;\n+ }\n+ return true;\n+ }\n+\nprivate static boolean isUserValid(KeycloakSession session, RealmModel realm, UserModel user, AccessToken token) {\nif (user == null || !user.isEnabled()) {\nlogger.debug(\"Unknown user in identity token\");\n@@ -1473,11 +1514,13 @@ public class AuthenticationManager {\nprivate final UserModel user;\nprivate final UserSessionModel session;\nprivate final AccessToken token;\n+ private final ClientModel client;\n- public AuthResult(UserModel user, UserSessionModel session, AccessToken token) {\n+ public AuthResult(UserModel user, UserSessionModel session, AccessToken token, ClientModel client) {\nthis.user = user;\nthis.session = session;\nthis.token = token;\n+ this.client = client;\n}\npublic UserSessionModel getSession() {\n@@ -1491,6 +1534,10 @@ public class AuthenticationManager {\npublic AccessToken getToken() {\nreturn token;\n}\n+\n+ public ClientModel getClient() {\n+ return client;\n+ }\n}\npublic static void setKcActionStatus(String executedProviderId, RequiredActionContext.KcActionStatus status, AuthenticationSessionModel authSession) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/IdentityBrokerService.java", "new_path": "services/src/main/java/org/keycloak/services/resources/IdentityBrokerService.java", "diff": "@@ -451,15 +451,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal\nif (authResult != null) {\nAccessToken token = authResult.getToken();\n- String issuedFor = token.getIssuedFor();\n- ClientModel clientModel = this.realmModel.getClientByClientId(issuedFor);\n-\n- if (clientModel == null) {\n- return badRequest(\"Invalid client.\");\n- }\n- if (!clientModel.isEnabled()) {\n- return badRequest(\"Client is disabled\");\n- }\n+ ClientModel clientModel = authResult.getClient();\nsession.getContext().setClient(clientModel);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/admin/AdminRoot.java", "new_path": "services/src/main/java/org/keycloak/services/resources/admin/AdminRoot.java", "diff": "@@ -179,13 +179,7 @@ public class AdminRoot {\nthrow new NotAuthorizedException(\"Bearer\");\n}\n- ClientModel client = realm.getClientByClientId(token.getIssuedFor());\n- if (client == null) {\n- throw new NotFoundException(\"Could not find client for authorization\");\n-\n- }\n-\n- return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);\n+ return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), authResult.getClient());\n}\npublic static UriBuilder realmsUrl(UriInfo uriInfo) {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/AdminClientTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/AdminClientTest.java", "diff": "@@ -20,11 +20,14 @@ package org.keycloak.testsuite.admin;\nimport java.util.List;\n+import javax.ws.rs.NotAuthorizedException;\n+\nimport org.junit.Assert;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.keycloak.admin.client.Keycloak;\n+import org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.common.constants.ServiceAccountConstants;\nimport org.keycloak.models.AdminRoles;\nimport org.keycloak.models.Constants;\n@@ -88,7 +91,9 @@ public class AdminClientTest extends AbstractKeycloakTest {\nUserBuilder defaultUser = UserBuilder.create()\n.id(KeycloakModelUtils.generateId())\n- .username(\"test-user@localhost\");\n+ .username(\"test-user@localhost\")\n+ .password(\"password\")\n+ .role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN);\nrealm.user(defaultUser);\ntestRealms.add(realm.build());\n@@ -103,9 +108,60 @@ public class AdminClientTest extends AbstractKeycloakTest {\nsetTimeOffset(1000);\n- // Check still possible to load the realm after token expired\n+ // Check still possible to load the realm after original token expired (admin client should automatically re-authenticate)\nrealm = adminClient.realm(\"test\").toRepresentation();\nAssert.assertEquals(\"test\", realm.getRealm());\n}\n}\n+\n+ @Test\n+ public void clientCredentialsClientDisabled() throws Exception {\n+ try (Keycloak adminClient = AdminClientUtil.createAdminClientWithClientCredentials(\"test\", \"service-account-cl\", \"secret1\")) {\n+ // Check possible to load the realm\n+ RealmRepresentation realm = adminClient.realm(\"test\").toRepresentation();\n+ Assert.assertEquals(\"test\", realm.getRealm());\n+\n+ // Disable client and check it should not be possible to load the realms anymore\n+ setClientEnabled(\"service-account-cl\", false);\n+\n+ // Check not possible to invoke anymore\n+ try {\n+ realm = adminClient.realm(\"test\").toRepresentation();\n+ Assert.fail(\"Not expected to successfully get realm\");\n+ } catch (NotAuthorizedException nae) {\n+ // Expected\n+ }\n+ } finally {\n+ setClientEnabled(\"service-account-cl\", true);\n+ }\n+ }\n+\n+ @Test\n+ public void adminAuthClientDisabled() throws Exception {\n+ try (Keycloak adminClient = AdminClientUtil.createAdminClient(false, \"test\", \"test-user@localhost\", \"password\", Constants.ADMIN_CLI_CLIENT_ID, null)) {\n+ // Check possible to load the realm\n+ RealmRepresentation realm = adminClient.realm(\"test\").toRepresentation();\n+ Assert.assertEquals(\"test\", realm.getRealm());\n+\n+ // Disable client and check it should not be possible to load the realms anymore\n+ setClientEnabled(Constants.ADMIN_CLI_CLIENT_ID, false);\n+\n+ // Check not possible to invoke anymore\n+ try {\n+ realm = adminClient.realm(\"test\").toRepresentation();\n+ Assert.fail(\"Not expected to successfully get realm\");\n+ } catch (NotAuthorizedException nae) {\n+ // Expected\n+ }\n+ } finally {\n+ setClientEnabled(Constants.ADMIN_CLI_CLIENT_ID, true);\n+ }\n+ }\n+\n+ private void setClientEnabled(String clientId, boolean enabled) {\n+ ClientResource client = ApiUtil.findClientByClientId(adminClient.realms().realm(\"test\"), clientId);\n+ ClientRepresentation clientRep = client.toRepresentation();\n+ clientRep.setEnabled(enabled);\n+ client.update(clientRep);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationTest.java", "diff": "@@ -30,10 +30,14 @@ import java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n+import javax.ws.rs.NotAuthorizedException;\n+import javax.ws.rs.client.Client;\n+import javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.Status;\nimport org.apache.commons.io.output.ByteArrayOutputStream;\nimport org.apache.http.NameValuePair;\n+import org.apache.http.client.HttpClient;\nimport org.apache.http.client.entity.UrlEncodedFormEntity;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpPost;\n@@ -41,25 +45,32 @@ import org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.message.BasicNameValuePair;\nimport org.jboss.arquillian.graphene.page.Page;\n+import org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.keycloak.OAuth2Constants;\nimport org.keycloak.OAuthErrorException;\n+import org.keycloak.admin.client.Keycloak;\nimport org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.admin.client.resource.UserResource;\n+import org.keycloak.broker.provider.util.SimpleHttp;\n+import org.keycloak.representations.account.UserRepresentation;\nimport org.keycloak.representations.idm.OAuth2ErrorRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.representations.idm.UserSessionRepresentation;\nimport org.keycloak.representations.oidc.TokenMetadataRepresentation;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\n+import org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.AssertEvents;\nimport org.keycloak.testsuite.pages.LoginPage;\n+import org.keycloak.testsuite.util.AdminClientUtil;\nimport org.keycloak.testsuite.util.ClientManager;\nimport org.keycloak.testsuite.util.Matchers;\nimport org.keycloak.testsuite.util.OAuthClient;\nimport org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse;\nimport org.keycloak.testsuite.util.RealmBuilder;\n+import org.keycloak.testsuite.util.UserInfoClientUtil;\nimport org.keycloak.util.JsonSerialization;\n/**\n@@ -69,6 +80,9 @@ public class TokenRevocationTest extends AbstractKeycloakTest {\nprivate RealmResource realm;\n+ private Client userInfoClient;\n+ private CloseableHttpClient restHttpClient;\n+\n@Rule\npublic AssertEvents events = new AssertEvents(this);\n@@ -87,10 +101,21 @@ public class TokenRevocationTest extends AbstractKeycloakTest {\n}\n@Before\n- public void clientConfiguration() {\n+ public void beforeTest() {\n+ // Create client configuration\nrealm = adminClient.realm(\"test\");\nClientManager.realm(realm).clientId(\"test-app\").directAccessGrant(true);\nClientManager.realm(realm).clientId(\"test-app-scope\").directAccessGrant(true);\n+\n+ // Create clients\n+ userInfoClient = AdminClientUtil.createResteasyClient();\n+ restHttpClient = HttpClientBuilder.create().build();\n+ }\n+\n+ @After\n+ public void afterTest() throws IOException {\n+ userInfoClient.close();\n+ restHttpClient.close();\n}\n@Page\n@@ -270,10 +295,32 @@ public class TokenRevocationTest extends AbstractKeycloakTest {\n}\nprivate void isAccessTokenDisabled(String accessTokenString, String clientId) throws IOException {\n+ // Test introspection endpoint not possible\nString introspectionResponse = oauth.introspectAccessTokenWithClientCredential(clientId, \"password\",\naccessTokenString);\nTokenMetadataRepresentation rep = JsonSerialization.readValue(introspectionResponse, TokenMetadataRepresentation.class);\nassertFalse(rep.isActive());\n+\n+ // Test userInfo endpoint not possible\n+ Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(userInfoClient, accessTokenString);\n+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());\n+\n+ // Test account REST not possible\n+ String accountUrl = OAuthClient.AUTH_SERVER_ROOT + \"/realms/test/account\";\n+ SimpleHttp accountRequest = SimpleHttp.doGet(accountUrl, restHttpClient)\n+ .auth(accessTokenString)\n+ .acceptJson();\n+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), accountRequest.asStatus());\n+\n+ // Test admin REST not possible\n+ try (Keycloak adminClient = Keycloak.getInstance(OAuthClient.AUTH_SERVER_ROOT, \"test\", \"test-app\", accessTokenString)) {\n+ try {\n+ adminClient.realms().realm(\"test\").toRepresentation();\n+ Assert.fail(\"Not expected to obtain realm\");\n+ } catch (NotAuthorizedException nae) {\n+ // Expected\n+ }\n+ }\n}\nprivate String doTokenRevokeWithDuplicateParams(String token, String tokenTypeHint, String clientSecret)\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Fixing for token revocation checks only (#9707) Closes #9705
339,281
02.02.2022 13:22:11
-3,600
165791b1d7554b83fbb41fc62fb829930cec83ce
Client Scopes: Ensure that parent's version ID is incremented when an attribute changes Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaChildEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaChildEntity.java", "diff": "*/\npackage org.keycloak.models.map.storage.jpa;\n+import java.io.Serializable;\n+\n/**\n* Interface for all child entities for JPA map storage.\n*/\n-public interface JpaChildEntity<R> {\n+public interface JpaChildEntity<R> extends Serializable {\n/**\n* Parent entity that should get its optimistic locking version updated upon changes in the child\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "diff": "*/\npackage org.keycloak.models.map.storage.jpa.client.entity;\n-import java.io.Serializable;\nimport java.util.Objects;\nimport java.util.UUID;\nimport javax.persistence.Column;\n@@ -32,7 +31,7 @@ import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n@Entity\n@Table(name = \"client_attribute\")\n-public class JpaClientAttributeEntity implements JpaChildEntity<JpaClientEntity>, Serializable {\n+public class JpaClientAttributeEntity implements JpaChildEntity<JpaClientEntity> {\n@Id\n@Column\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeAttributeEntity.java", "diff": "*/\npackage org.keycloak.models.map.storage.jpa.clientscope.entity;\n-import java.io.Serializable;\nimport java.util.Objects;\nimport java.util.UUID;\nimport javax.persistence.Column;\n@@ -28,10 +27,11 @@ import javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\nimport org.hibernate.annotations.Nationalized;\n+import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n@Entity\n@Table(name = \"client_scope_attribute\")\n-public class JpaClientScopeAttributeEntity implements Serializable {\n+public class JpaClientScopeAttributeEntity implements JpaChildEntity<JpaClientScopeEntity> {\n@Id\n@Column\n@@ -100,4 +100,9 @@ public class JpaClientScopeAttributeEntity implements Serializable {\nObjects.equals(getName(), that.getName()) &&\nObjects.equals(getValue(), that.getValue());\n}\n+\n+ @Override\n+ public JpaClientScopeEntity getParent() {\n+ return getClientScope();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "diff": "@@ -230,7 +230,6 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\nJpaClientScopeAttributeEntity attr = iterator.next();\nif (Objects.equals(attr.getName(), name)) {\niterator.remove();\n- attr.setClientScope(null);\n}\n}\n}\n@@ -268,9 +267,7 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\npublic void setAttributes(Map<String, List<String>> attributes) {\ncheckEntityVersionForUpdate();\nfor (Iterator<JpaClientScopeAttributeEntity> iterator = this.attributes.iterator(); iterator.hasNext();) {\n- JpaClientScopeAttributeEntity attr = iterator.next();\niterator.remove();\n- attr.setClientScope(null);\n}\nif (attributes != null) {\nfor (Map.Entry<String, List<String>> attrEntry : attributes.entrySet()) {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "diff": "*/\npackage org.keycloak.models.map.storage.jpa.role.entity;\n-import java.io.Serializable;\nimport java.util.Objects;\nimport java.util.UUID;\nimport javax.persistence.Column;\n@@ -29,11 +28,10 @@ import javax.persistence.ManyToOne;\nimport javax.persistence.Table;\nimport org.hibernate.annotations.Nationalized;\nimport org.keycloak.models.map.storage.jpa.JpaChildEntity;\n-import org.keycloak.models.map.storage.jpa.client.entity.JpaClientEntity;\n@Entity\n@Table(name = \"role_attribute\")\n-public class JpaRoleAttributeEntity implements JpaChildEntity<JpaRoleEntity>, Serializable {\n+public class JpaRoleAttributeEntity implements JpaChildEntity<JpaRoleEntity> {\n@Id\n@Column\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Client Scopes: Ensure that parent's version ID is incremented when an attribute changes Closes #9874
339,281
02.02.2022 13:55:09
-3,600
7bd0dbb3ce2dd5bf3a338b1ad7c789fddf8255ee
Client Scopes: Added ModelIllegalStateException to handle lazy loading exception. Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/delegate/JpaClientScopeDelegateProvider.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/delegate/JpaClientScopeDelegateProvider.java", "diff": "@@ -28,47 +28,47 @@ import org.keycloak.models.map.clientscope.MapClientScopeEntity;\nimport org.keycloak.models.map.clientscope.MapClientScopeEntityFields;\nimport org.keycloak.models.map.common.EntityField;\nimport org.keycloak.models.map.common.delegate.DelegateProvider;\n+import org.keycloak.models.map.storage.jpa.JpaDelegateProvider;\nimport org.keycloak.models.map.storage.jpa.clientscope.entity.JpaClientScopeEntity;\n-public class JpaClientScopeDelegateProvider implements DelegateProvider<MapClientScopeEntity> {\n+public class JpaClientScopeDelegateProvider extends JpaDelegateProvider<JpaClientScopeEntity> implements DelegateProvider<MapClientScopeEntity> {\n- private JpaClientScopeEntity delegate;\nprivate final EntityManager em;\npublic JpaClientScopeDelegateProvider(JpaClientScopeEntity delegate, EntityManager em) {\n- this.delegate = delegate;\n+ super(delegate);\nthis.em = em;\n}\n@Override\npublic MapClientScopeEntity getDelegate(boolean isRead, Enum<? extends EntityField<MapClientScopeEntity>> field, Object... parameters) {\n- if (delegate.isMetadataInitialized()) return delegate;\n+ if (getDelegate().isMetadataInitialized()) return getDelegate();\nif (isRead) {\nif (field instanceof MapClientScopeEntityFields) {\nswitch ((MapClientScopeEntityFields) field) {\ncase ID:\ncase REALM_ID:\ncase NAME:\n- return delegate;\n+ return getDelegate();\ncase ATTRIBUTES:\nCriteriaBuilder cb = em.getCriteriaBuilder();\nCriteriaQuery<JpaClientScopeEntity> query = cb.createQuery(JpaClientScopeEntity.class);\nRoot<JpaClientScopeEntity> root = query.from(JpaClientScopeEntity.class);\nroot.fetch(\"attributes\", JoinType.INNER);\n- query.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(delegate.getId())));\n+ query.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(getDelegate().getId())));\n- delegate = em.createQuery(query).getSingleResult();\n+ setDelegate(em.createQuery(query).getSingleResult());\nbreak;\ndefault:\n- delegate = em.find(JpaClientScopeEntity.class, UUID.fromString(delegate.getId()));\n+ setDelegate(em.find(JpaClientScopeEntity.class, UUID.fromString(getDelegate().getId())));\n}\n} else throw new IllegalStateException(\"Not a valid client scope field: \" + field);\n} else {\n- delegate = em.find(JpaClientScopeEntity.class, UUID.fromString(delegate.getId()));\n+ setDelegate(em.find(JpaClientScopeEntity.class, UUID.fromString(getDelegate().getId())));\n}\n- return delegate;\n+ return getDelegate();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "diff": "@@ -135,6 +135,7 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\nmetadata.setEntityVersion(entityVersion);\n}\n+ @Override\npublic int getVersion() {\nreturn version;\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Client Scopes: Added ModelIllegalStateException to handle lazy loading exception. Closes #9645
339,425
01.02.2022 19:06:47
-3,600
db4642d2500134546dbd42235ebd7533e82c25cb
[fixes - Enable Dynamic Scopes for the resource-owner-password-credentials grant Change some calls to the new AuthorizationContextUtil class and add tests for the client-credentials grant
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "diff": "@@ -640,6 +640,9 @@ public class TokenManager {\n* @return\n*/\npublic static boolean isValidScope(String scopes, AuthorizationRequestContext authorizationRequestContext, ClientModel client) {\n+ if (scopes == null) {\n+ return true;\n+ }\nif (authorizationRequestContext.getAuthorizationDetailEntries() == null || authorizationRequestContext.getAuthorizationDetailEntries().isEmpty()) {\nreturn false;\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java", "diff": "@@ -62,6 +62,7 @@ import org.keycloak.protocol.oidc.utils.PkceUtils;\nimport org.keycloak.protocol.saml.JaxrsSAML2BindingBuilder;\nimport org.keycloak.protocol.saml.SamlClient;\nimport org.keycloak.protocol.saml.SamlProtocol;\n+import org.keycloak.rar.AuthorizationRequestContext;\nimport org.keycloak.representations.AccessToken;\nimport org.keycloak.representations.AccessTokenResponse;\nimport org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata;\n@@ -84,6 +85,7 @@ import org.keycloak.services.managers.AuthenticationSessionManager;\nimport org.keycloak.services.managers.ClientManager;\nimport org.keycloak.services.managers.RealmManager;\nimport org.keycloak.services.resources.Cors;\n+import org.keycloak.services.util.AuthorizationContextUtil;\nimport org.keycloak.services.util.DefaultClientSessionContext;\nimport org.keycloak.services.util.MtlsHoKTokenUtil;\nimport org.keycloak.sessions.AuthenticationSessionModel;\n@@ -804,7 +806,15 @@ public class TokenEndpoint {\nprivate String getRequestedScopes() {\nString scope = formParams.getFirst(OAuth2Constants.SCOPE);\n- if (!TokenManager.isValidScope(scope, client)) {\n+ boolean validScopes;\n+ if (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n+ AuthorizationRequestContext authorizationRequestContext = AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, scope);\n+ validScopes = TokenManager.isValidScope(scope, authorizationRequestContext, client);\n+ } else {\n+ validScopes = TokenManager.isValidScope(scope, client);\n+ }\n+\n+ if (!validScopes) {\nevent.error(Errors.INVALID_REQUEST);\nthrow new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, \"Invalid scopes: \" + scope,\nStatus.BAD_REQUEST);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/request/AuthorizationEndpointRequestParserProcessor.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/request/AuthorizationEndpointRequestParserProcessor.java", "diff": "@@ -28,12 +28,11 @@ import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\nimport org.keycloak.protocol.oidc.OIDCConfigAttributes;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.protocol.oidc.par.endpoints.request.AuthzEndpointParParser;\n-import org.keycloak.protocol.oidc.rar.AuthorizationRequestParserProvider;\n-import org.keycloak.protocol.oidc.rar.parsers.ClientScopeAuthorizationRequestParserProviderFactory;\nimport org.keycloak.protocol.oidc.utils.RedirectUtils;\nimport org.keycloak.services.ErrorPageException;\nimport org.keycloak.services.ServicesLogger;\nimport org.keycloak.services.messages.Messages;\n+import org.keycloak.services.util.AuthorizationContextUtil;\nimport javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.core.Response;\n@@ -100,15 +99,7 @@ public class AuthorizationEndpointRequestParserProcessor {\n}\nif (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n- AuthorizationRequestParserProvider clientScopeParser = session.getProvider(AuthorizationRequestParserProvider.class,\n- ClientScopeAuthorizationRequestParserProviderFactory.CLIENT_SCOPE_PARSER_ID);\n-\n- if (clientScopeParser == null) {\n- throw new RuntimeException(String.format(\"No provider found for authorization requests parser %1s\",\n- ClientScopeAuthorizationRequestParserProviderFactory.CLIENT_SCOPE_PARSER_ID));\n- }\n-\n- request.authorizationRequestContext = clientScopeParser.parseScopes(request.getScope());\n+ request.authorizationRequestContext = AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, request.getScope());\n}\nreturn request;\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java", "new_path": "services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java", "diff": "@@ -81,6 +81,7 @@ import org.keycloak.services.messages.Messages;\nimport org.keycloak.services.resources.IdentityBrokerService;\nimport org.keycloak.services.resources.LoginActionsService;\nimport org.keycloak.services.resources.RealmsResource;\n+import org.keycloak.services.util.AuthorizationContextUtil;\nimport org.keycloak.services.util.CookieHelper;\nimport org.keycloak.services.util.DefaultClientSessionContext;\nimport org.keycloak.services.util.P3PHelper;\n@@ -1190,7 +1191,7 @@ public class AuthenticationManager {\n//if Dynamic Scopes are enabled, get the scopes from the AuthorizationRequestContext, passing the session and scopes as parameters\n// then concat a Stream with the ClientModel, as it's discarded in the getAuthorizationRequestContext method\nif (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n- return Stream.concat(DefaultClientSessionContext.getAuthorizationRequestContext(session, authSession.getClientNote(OAuth2Constants.SCOPE))\n+ return Stream.concat(AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, authSession.getClientNote(OAuth2Constants.SCOPE))\n.getAuthorizationDetailEntries().stream(),\nCollections.singletonList(new AuthorizationDetails(session.getContext().getClient())).stream());\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "services/src/main/java/org/keycloak/services/util/AuthorizationContextUtil.java", "diff": "+package org.keycloak.services.util;\n+\n+import org.keycloak.common.Profile;\n+import org.keycloak.models.KeycloakSession;\n+import org.keycloak.protocol.oidc.rar.AuthorizationRequestParserProvider;\n+import org.keycloak.protocol.oidc.rar.parsers.ClientScopeAuthorizationRequestParserProviderFactory;\n+import org.keycloak.rar.AuthorizationRequestContext;\n+\n+public class AuthorizationContextUtil {\n+\n+ public static AuthorizationRequestContext getAuthorizationRequestContextFromScopes(KeycloakSession session, String scope) {\n+ if (!Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n+ throw new RuntimeException(\"The Dynamic Scopes feature is not enabled and the AuthorizationRequestContext hasn't been generated\");\n+ }\n+ AuthorizationRequestParserProvider clientScopeParser = session.getProvider(AuthorizationRequestParserProvider.class,\n+ ClientScopeAuthorizationRequestParserProviderFactory.CLIENT_SCOPE_PARSER_ID);\n+\n+ if (clientScopeParser == null) {\n+ throw new RuntimeException(String.format(\"No provider found for authorization requests parser %1s\",\n+ ClientScopeAuthorizationRequestParserProviderFactory.CLIENT_SCOPE_PARSER_ID));\n+ }\n+\n+ return clientScopeParser.parseScopes(scope);\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/util/DefaultClientSessionContext.java", "new_path": "services/src/main/java/org/keycloak/services/util/DefaultClientSessionContext.java", "diff": "@@ -42,8 +42,6 @@ import org.keycloak.models.utils.RoleUtils;\nimport org.keycloak.protocol.ProtocolMapperUtils;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.protocol.oidc.TokenManager;\n-import org.keycloak.protocol.oidc.rar.AuthorizationRequestParserProvider;\n-import org.keycloak.protocol.oidc.rar.parsers.ClientScopeAuthorizationRequestParserProviderFactory;\nimport org.keycloak.rar.AuthorizationRequestContext;\nimport org.keycloak.rar.AuthorizationRequestSource;\nimport org.keycloak.util.TokenUtil;\n@@ -192,7 +190,7 @@ public class DefaultClientSessionContext implements ClientSessionContext {\n* @return see description\n*/\nprivate String buildScopesStringFromAuthorizationRequest() {\n- return this.getAuthorizationRequestContext().getAuthorizationDetailEntries().stream()\n+ return AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, clientSession.getNote(OAuth2Constants.SCOPE)).getAuthorizationDetailEntries().stream()\n.filter(authorizationDetails -> authorizationDetails.getSource().equals(AuthorizationRequestSource.SCOPE))\n.filter(authorizationDetails -> authorizationDetails.getClientScope().isIncludeInTokenScope())\n.filter(authorizationDetails -> isClientScopePermittedForUser(authorizationDetails.getClientScope()))\n@@ -215,22 +213,7 @@ public class DefaultClientSessionContext implements ClientSessionContext {\n@Override\npublic AuthorizationRequestContext getAuthorizationRequestContext() {\n- return DefaultClientSessionContext.getAuthorizationRequestContext(this.session, clientSession.getNote(OAuth2Constants.SCOPE));\n- }\n-\n- public static AuthorizationRequestContext getAuthorizationRequestContext(KeycloakSession keycloakSession, String scopes) {\n- if(!Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n- throw new RuntimeException(\"The Dynamic Scopes feature is not enabled and the AuthorizationRequestContext hasn't been generated\");\n- }\n- AuthorizationRequestParserProvider clientScopeParser = keycloakSession.getProvider(AuthorizationRequestParserProvider.class,\n- ClientScopeAuthorizationRequestParserProviderFactory.CLIENT_SCOPE_PARSER_ID);\n-\n- if(clientScopeParser == null) {\n- throw new RuntimeException(String.format(\"No provider found for authorization requests parser %1s\",\n- ClientScopeAuthorizationRequestParserProviderFactory.CLIENT_SCOPE_PARSER_ID));\n- }\n-\n- return clientScopeParser.parseScopes(scopes);\n+ return AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, clientSession.getNote(OAuth2Constants.SCOPE));\n}\n// Loading data\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ResourceOwnerPasswordCredentialsGrantTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ResourceOwnerPasswordCredentialsGrantTest.java", "diff": "@@ -29,27 +29,34 @@ import org.junit.Rule;\nimport org.junit.Test;\nimport org.keycloak.OAuth2Constants;\nimport org.keycloak.OAuthErrorException;\n+import org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.authentication.authenticators.client.ClientIdAndSecretAuthenticator;\n+import org.keycloak.common.Profile;\nimport org.keycloak.connections.infinispan.InfinispanConnectionProvider;\nimport org.keycloak.crypto.Algorithm;\nimport org.keycloak.events.Details;\nimport org.keycloak.events.Errors;\nimport org.keycloak.jose.jws.JWSHeader;\nimport org.keycloak.jose.jws.JWSInput;\n+import org.keycloak.models.ClientScopeModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.utils.KeycloakModelUtils;\nimport org.keycloak.models.utils.TimeBasedOTP;\nimport org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\n+import org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.representations.AccessToken;\nimport org.keycloak.representations.RefreshToken;\nimport org.keycloak.representations.idm.ClientRepresentation;\n+import org.keycloak.representations.idm.ClientScopeRepresentation;\n+import org.keycloak.representations.idm.EventRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.representations.idm.UserRepresentation;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.AssertEvents;\nimport org.keycloak.testsuite.admin.ApiUtil;\n+import org.keycloak.testsuite.arquillian.annotation.EnableFeature;\nimport org.keycloak.testsuite.util.ClientBuilder;\nimport org.keycloak.testsuite.util.ClientManager;\nimport org.keycloak.testsuite.util.OAuthClient;\n@@ -61,15 +68,19 @@ import org.keycloak.testsuite.util.UserManager;\nimport java.io.UnsupportedEncodingException;\nimport java.security.Security;\n+import java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\n+import static org.junit.Assert.assertTrue;\n+import javax.validation.constraints.AssertTrue;\nimport javax.ws.rs.core.HttpHeaders;\nimport javax.ws.rs.core.MediaType;\n+import javax.ws.rs.core.Response;\n/**\n* @author <a href=\"mailto:[email protected]\">Stian Thorgersen</a>\n@@ -178,6 +189,65 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT\ngrantAccessToken(\"direct-login\", \"resource-owner-public\");\n}\n+ @Test\n+ @EnableFeature(value = Profile.Feature.DYNAMIC_SCOPES, skipRestart = true)\n+ public void grantAccessTokenWithDynamicScope() throws Exception {\n+ ClientScopeRepresentation clientScope = new ClientScopeRepresentation();\n+ clientScope.setName(\"dynamic-scope\");\n+ clientScope.setAttributes(new HashMap<String, String>() {{\n+ put(ClientScopeModel.IS_DYNAMIC_SCOPE, \"true\");\n+ put(ClientScopeModel.DYNAMIC_SCOPE_REGEXP, \"dynamic-scope:*\");\n+ }});\n+ clientScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);\n+ RealmResource realmResource = adminClient.realm(\"test\");\n+ try(Response response = realmResource.clientScopes().create(clientScope)) {\n+ String scopeId = ApiUtil.getCreatedId(response);\n+ getCleanup().addClientScopeId(scopeId);\n+ ClientResource resourceOwnerPublicClient = ApiUtil.findClientByClientId(realmResource, \"resource-owner-public\");\n+ ClientRepresentation testAppRep = resourceOwnerPublicClient.toRepresentation();\n+ resourceOwnerPublicClient.update(testAppRep);\n+ resourceOwnerPublicClient.addOptionalClientScope(scopeId);\n+ }\n+\n+ oauth.scope(\"dynamic-scope:123\");\n+ oauth.clientId(\"resource-owner-public\");\n+\n+ OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(\"secret\", \"direct-login\", \"password\");\n+\n+ assertTrue(response.getScope().contains(\"dynamic-scope:123\"));\n+\n+ assertEquals(200, response.getStatusCode());\n+\n+ AccessToken accessToken = oauth.verifyToken(response.getAccessToken());\n+ RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());\n+\n+ events.expectLogin()\n+ .client(\"resource-owner-public\")\n+ .user(userId)\n+ .session(accessToken.getSessionState())\n+ .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD)\n+ .detail(Details.TOKEN_ID, accessToken.getId())\n+ .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())\n+ .detail(Details.USERNAME, \"direct-login\")\n+ .removeDetail(Details.CODE_ID)\n+ .removeDetail(Details.REDIRECT_URI)\n+ .removeDetail(Details.CONSENT)\n+ .assertEvent();\n+\n+ assertTrue(accessToken.getScope().contains(\"dynamic-scope:123\"));\n+ }\n+\n+ @Test\n+ @EnableFeature(value = Profile.Feature.DYNAMIC_SCOPES, skipRestart = true)\n+ public void grantAccessTokenWithUnassignedDynamicScope() throws Exception {;\n+ oauth.scope(\"unknown-scope:123\");\n+ oauth.clientId(\"resource-owner-public\");\n+ OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(\"secret\", \"direct-login\", \"password\");\n+ assertEquals(400, response.getStatusCode());\n+ assertEquals(\"invalid_scope\", response.getError());\n+ assertEquals(\"Invalid scopes: unknown-scope:123\", response.getErrorDescription());\n+ }\n+\n@Test\npublic void grantAccessTokenWithTotp() throws Exception {\ngrantAccessToken(userId2, \"direct-login-otp\", \"resource-owner\", totp.generateTOTP(\"totpSecret\"));\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/rar/AbstractRARParserTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/rar/AbstractRARParserTest.java", "diff": "@@ -19,19 +19,18 @@ package org.keycloak.testsuite.rar;\nimport org.junit.Before;\nimport org.junit.Rule;\n+import org.keycloak.OAuth2Constants;\nimport org.keycloak.common.Profile;\nimport org.keycloak.models.AuthenticatedClientSessionModel;\nimport org.keycloak.models.ClientModel;\n-import org.keycloak.models.ClientSessionContext;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.UserSessionModel;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.representations.idm.UserRepresentation;\n-import org.keycloak.services.util.DefaultClientSessionContext;\n+import org.keycloak.services.util.AuthorizationContextUtil;\nimport org.keycloak.testsuite.AbstractTestRealmKeycloakTest;\nimport org.keycloak.testsuite.AssertEvents;\n-import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\nimport org.keycloak.testsuite.arquillian.annotation.EnableFeature;\nimport org.keycloak.testsuite.util.ClientManager;\nimport org.keycloak.testsuite.util.RealmBuilder;\n@@ -96,9 +95,9 @@ public abstract class AbstractRARParserTest extends AbstractTestRealmKeycloakTes\nfinal ClientModel client = realm.getClientByClientId(\"test-app\");\nString clientUUID = client.getId();\nAuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(clientUUID);\n- ClientSessionContext clientSessionContext = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, session);\nsession.getContext().setClient(client);\n- List<AuthorizationRequestContextHolder.AuthorizationRequestHolder> authorizationRequestHolders = clientSessionContext.getAuthorizationRequestContext().getAuthorizationDetailEntries().stream()\n+ List<AuthorizationRequestContextHolder.AuthorizationRequestHolder> authorizationRequestHolders = AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, clientSession.getNote(OAuth2Constants.SCOPE))\n+ .getAuthorizationDetailEntries().stream()\n.map(AuthorizationRequestContextHolder.AuthorizationRequestHolder::new)\n.collect(Collectors.toList());\nreturn new AuthorizationRequestContextHolder(authorizationRequestHolders);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[fixes #9919] - Enable Dynamic Scopes for the resource-owner-password-credentials grant Change some calls to the new AuthorizationContextUtil class and add tests for the client-credentials grant
339,156
21.01.2022 09:50:29
-7,200
a1f2f77b82790d7cb785d2e2ef368c9eb43e48c7
Device Authorization Grant with PKCE Closes
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/models/OAuth2DeviceCodeModel.java", "new_path": "server-spi-private/src/main/java/org/keycloak/models/OAuth2DeviceCodeModel.java", "diff": "@@ -39,6 +39,8 @@ public class OAuth2DeviceCodeModel {\nprivate static final String USER_SESSION_ID_NOTE = \"uid\";\nprivate static final String DENIED_NOTE = \"denied\";\nprivate static final String ADDITIONAL_PARAM_PREFIX = \"additional_param_\";\n+ private static final String CODE_CHALLENGE = \"codeChallenge\";\n+ private static final String CODE_CHALLENGE_METHOD = \"codeChallengeMethod\";\nprivate final RealmModel realm;\nprivate final String clientId;\n@@ -52,33 +54,35 @@ public class OAuth2DeviceCodeModel {\nprivate final String userSessionId;\nprivate final Boolean denied;\nprivate final Map<String, String> additionalParams;\n+ private final String codeChallenge;\n+ private final String codeChallengeMethod;\npublic static OAuth2DeviceCodeModel create(RealmModel realm, ClientModel client,\nString deviceCode, String scope, String nonce, int expiresIn, int pollingInterval,\n- String clientNotificationToken, String authReqId, Map<String, String> additionalParams) {\n+ String clientNotificationToken, String authReqId, Map<String, String> additionalParams, String codeChallenge, String codeChallengeMethod) {\nint expiration = Time.currentTime() + expiresIn;\n- return new OAuth2DeviceCodeModel(realm, client.getClientId(), deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, null, null, additionalParams);\n+ return new OAuth2DeviceCodeModel(realm, client.getClientId(), deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, null, null, additionalParams, codeChallenge, codeChallengeMethod);\n}\npublic OAuth2DeviceCodeModel approve(String userSessionId) {\n- return new OAuth2DeviceCodeModel(realm, clientId, deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, userSessionId, false, additionalParams);\n+ return new OAuth2DeviceCodeModel(realm, clientId, deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, userSessionId, false, additionalParams, codeChallenge, codeChallengeMethod);\n}\npublic OAuth2DeviceCodeModel approve(String userSessionId, Map<String, String> additionalParams) {\nif (additionalParams != null) {\nthis.additionalParams.putAll(additionalParams);\n}\n- return new OAuth2DeviceCodeModel(realm, clientId, deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, userSessionId, false, this.additionalParams);\n+ return new OAuth2DeviceCodeModel(realm, clientId, deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, userSessionId, false, this.additionalParams, codeChallenge, codeChallengeMethod);\n}\npublic OAuth2DeviceCodeModel deny() {\n- return new OAuth2DeviceCodeModel(realm, clientId, deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, null, true, additionalParams);\n+ return new OAuth2DeviceCodeModel(realm, clientId, deviceCode, scope, nonce, expiration, pollingInterval, clientNotificationToken, authReqId, null, true, additionalParams, codeChallenge, codeChallengeMethod);\n}\nprivate OAuth2DeviceCodeModel(RealmModel realm, String clientId,\nString deviceCode, String scope, String nonce, int expiration, int pollingInterval, String clientNotificationToken,\n- String authReqId, String userSessionId, Boolean denied, Map<String, String> additionalParams) {\n+ String authReqId, String userSessionId, Boolean denied, Map<String, String> additionalParams, String codeChallenge, String codeChallengeMethod) {\nthis.realm = realm;\nthis.clientId = clientId;\nthis.deviceCode = deviceCode;\n@@ -91,6 +95,8 @@ public class OAuth2DeviceCodeModel {\nthis.userSessionId = userSessionId;\nthis.denied = denied;\nthis.additionalParams = additionalParams;\n+ this.codeChallenge = codeChallenge;\n+ this.codeChallengeMethod = codeChallengeMethod;\n}\npublic static OAuth2DeviceCodeModel fromCache(RealmModel realm, String deviceCode, Map<String, String> data) {\n@@ -106,7 +112,7 @@ public class OAuth2DeviceCodeModel {\nprivate OAuth2DeviceCodeModel(RealmModel realm, String deviceCode, Map<String, String> data) {\nthis(realm, data.get(CLIENT_ID), deviceCode, data.get(SCOPE_NOTE), data.get(NONCE_NOTE),\nInteger.parseInt(data.get(EXPIRATION_NOTE)), Integer.parseInt(data.get(POLLING_INTERVAL_NOTE)), data.get(CLIENT_NOTIFICATION_TOKEN_NOTE),\n- data.get(AUTH_REQ_ID_NOTE), data.get(USER_SESSION_ID_NOTE), Boolean.parseBoolean(data.get(DENIED_NOTE)), extractAdditionalParams(data));\n+ data.get(AUTH_REQ_ID_NOTE), data.get(USER_SESSION_ID_NOTE), Boolean.parseBoolean(data.get(DENIED_NOTE)), extractAdditionalParams(data), data.get(CODE_CHALLENGE), data.get(CODE_CHALLENGE_METHOD));\n}\nprivate static Map<String, String> extractAdditionalParams(Map<String, String> data) {\n@@ -175,6 +181,14 @@ public class OAuth2DeviceCodeModel {\nreturn createKey(deviceCode) + \".polling\";\n}\n+ public String getCodeChallenge() {\n+ return codeChallenge;\n+ }\n+\n+ public String getCodeChallengeMethod() {\n+ return codeChallengeMethod;\n+ }\n+\npublic Map<String, String> toMap() {\nMap<String, String> result = new HashMap<>();\n@@ -203,6 +217,10 @@ public class OAuth2DeviceCodeModel {\nresult.put(NONCE_NOTE, nonce);\nresult.put(USER_SESSION_ID_NOTE, userSessionId);\n}\n+ if (codeChallenge != null)\n+ result.put(CODE_CHALLENGE, codeChallenge);\n+ if (codeChallengeMethod != null)\n+ result.put(CODE_CHALLENGE_METHOD, codeChallengeMethod);\nadditionalParams.forEach((key, value) -> result.put(ADDITIONAL_PARAM_PREFIX + key, value));\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpointChecker.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpointChecker.java", "diff": "@@ -244,7 +244,7 @@ public class AuthorizationEndpointChecker {\n// PKCE not adopted to OAuth2 Implicit Grant and OIDC Implicit Flow,\n// adopted to OAuth2 Authorization Code Grant and OIDC Authorization Code Flow, Hybrid Flow\n// Namely, flows using authorization code.\n- if (parsedResponseType.isImplicitFlow()) return;\n+ if (parsedResponseType != null && parsedResponseType.isImplicitFlow()) return;\nString pkceCodeChallengeMethod = OIDCAdvancedConfigWrapper.fromClientModel(client).getPkceCodeChallengeMethod();\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java", "diff": "@@ -114,8 +114,6 @@ import java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.function.Supplier;\n-import java.util.regex.Matcher;\n-import java.util.regex.Pattern;\nimport java.util.stream.Stream;\n/**\n@@ -132,9 +130,6 @@ public class TokenEndpoint {\nAUTHORIZATION_CODE, REFRESH_TOKEN, PASSWORD, CLIENT_CREDENTIALS, TOKEN_EXCHANGE, PERMISSION, OAUTH2_DEVICE_CODE, CIBA\n}\n- // https://tools.ietf.org/html/rfc7636#section-4.2\n- private static final Pattern VALID_CODE_VERIFIER_PATTERN = Pattern.compile(\"^[0-9a-zA-Z\\\\-\\\\.~_]+$\");\n-\n@Context\nprivate KeycloakSession session;\n@@ -404,10 +399,10 @@ public class TokenEndpoint {\n}\nif (codeChallengeMethod != null && !codeChallengeMethod.isEmpty()) {\n- checkParamsForPkceEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername);\n+ PkceUtils.checkParamsForPkceEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);\n} else {\n// PKCE Activation is OFF, execute the codes implemented in KEYCLOAK-2604\n- checkParamsForPkceNotEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername);\n+ PkceUtils.checkParamsForPkceNotEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);\n}\ntry {\n@@ -491,63 +486,6 @@ public class TokenEndpoint {\n}\n}\n- private void checkParamsForPkceEnforcedClient(String codeVerifier, String codeChallenge, String codeChallengeMethod, String authUserId, String authUsername) {\n- // check whether code verifier is specified\n- if (codeVerifier == null) {\n- logger.warnf(\"PKCE code verifier not specified, authUserId = %s, authUsername = %s\", authUserId, authUsername);\n- event.error(Errors.CODE_VERIFIER_MISSING);\n- throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE code verifier not specified\", Response.Status.BAD_REQUEST);\n- }\n- verifyCodeVerifier(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername);\n- }\n-\n- private void checkParamsForPkceNotEnforcedClient(String codeVerifier, String codeChallenge, String codeChallengeMethod, String authUserId, String authUsername) {\n- if (codeChallenge != null && codeVerifier == null) {\n- logger.warnf(\"PKCE code verifier not specified, authUserId = %s, authUsername = %s\", authUserId, authUsername);\n- event.error(Errors.CODE_VERIFIER_MISSING);\n- throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE code verifier not specified\", Response.Status.BAD_REQUEST);\n- }\n-\n- if (codeChallenge != null) {\n- verifyCodeVerifier(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername);\n- }\n- }\n-\n- private void verifyCodeVerifier(String codeVerifier, String codeChallenge, String codeChallengeMethod, String authUserId, String authUsername) {\n- // check whether code verifier is formatted along with the PKCE specification\n-\n- if (!isValidPkceCodeVerifier(codeVerifier)) {\n- logger.infof(\"PKCE invalid code verifier\");\n- event.error(Errors.INVALID_CODE_VERIFIER);\n- throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE invalid code verifier\", Response.Status.BAD_REQUEST);\n- }\n-\n- logger.debugf(\"PKCE supporting Client, codeVerifier = %s\", codeVerifier);\n- String codeVerifierEncoded = codeVerifier;\n- try {\n- // https://tools.ietf.org/html/rfc7636#section-4.2\n- // plain or S256\n- if (codeChallengeMethod != null && codeChallengeMethod.equals(OAuth2Constants.PKCE_METHOD_S256)) {\n- logger.debugf(\"PKCE codeChallengeMethod = %s\", codeChallengeMethod);\n- codeVerifierEncoded = PkceUtils.generateS256CodeChallenge(codeVerifier);\n- } else {\n- logger.debug(\"PKCE codeChallengeMethod is plain\");\n- codeVerifierEncoded = codeVerifier;\n- }\n- } catch (Exception nae) {\n- logger.infof(\"PKCE code verification failed, not supported algorithm specified\");\n- event.error(Errors.PKCE_VERIFICATION_FAILED);\n- throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE code verification failed, not supported algorithm specified\", Response.Status.BAD_REQUEST);\n- }\n- if (!codeChallenge.equals(codeVerifierEncoded)) {\n- logger.warnf(\"PKCE verification failed. authUserId = %s, authUsername = %s\", authUserId, authUsername);\n- event.error(Errors.PKCE_VERIFICATION_FAILED);\n- throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE verification failed\", Response.Status.BAD_REQUEST);\n- } else {\n- logger.debugf(\"PKCE verification success. codeVerifierEncoded = %s, codeChallenge = %s\", codeVerifierEncoded, codeChallenge);\n- }\n- }\n-\npublic Response refreshTokenGrant() {\nString refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);\nif (refreshToken == null) {\n@@ -1003,20 +941,6 @@ public class TokenEndpoint {\nreturn grantType.cibaGrant();\n}\n- // https://tools.ietf.org/html/rfc7636#section-4.1\n- private boolean isValidPkceCodeVerifier(String codeVerifier) {\n- if (codeVerifier.length() < OIDCLoginProtocol.PKCE_CODE_VERIFIER_MIN_LENGTH) {\n- logger.infof(\" Error: PKCE codeVerifier length under lower limit , codeVerifier = %s\", codeVerifier);\n- return false;\n- }\n- if (codeVerifier.length() > OIDCLoginProtocol.PKCE_CODE_VERIFIER_MAX_LENGTH) {\n- logger.infof(\" Error: PKCE codeVerifier length over upper limit , codeVerifier = %s\", codeVerifier);\n- return false;\n- }\n- Matcher m = VALID_CODE_VERIFIER_PATTERN.matcher(codeVerifier);\n- return m.matches();\n- }\n-\npublic static class TokenExchangeSamlProtocol extends SamlProtocol {\nfinal SamlClient samlClient;\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/ciba/endpoints/BackchannelAuthenticationEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/ciba/endpoints/BackchannelAuthenticationEndpoint.java", "diff": "@@ -139,7 +139,7 @@ public class BackchannelAuthenticationEndpoint extends AbstractCibaEndpoint {\nOAuth2DeviceCodeModel deviceCode = OAuth2DeviceCodeModel.create(realm, client,\nrequest.getId(), request.getScope(), null, expiresIn, poolingInterval, request.getClientNotificationToken(), authReqId,\n- Collections.emptyMap());\n+ Collections.emptyMap(), null, null);\nString authResultId = request.getAuthResultId();\nOAuth2DeviceUserCodeModel userCode = new OAuth2DeviceUserCodeModel(realm, deviceCode.getDeviceCode(),\nauthResultId);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/device/DeviceGrantType.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/device/DeviceGrantType.java", "diff": "@@ -44,6 +44,7 @@ import org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint;\nimport org.keycloak.protocol.oidc.endpoints.TokenEndpoint;\nimport org.keycloak.protocol.oidc.grants.device.clientpolicy.context.DeviceTokenRequestContext;\nimport org.keycloak.protocol.oidc.grants.device.endpoints.DeviceEndpoint;\n+import org.keycloak.protocol.oidc.utils.PkceUtils;\nimport org.keycloak.services.CorsErrorResponseException;\nimport org.keycloak.services.clientpolicy.ClientPolicyException;\nimport org.keycloak.services.managers.AuthenticationManager;\n@@ -212,6 +213,18 @@ public class DeviceGrantType {\n\"The authorization request is still pending\", Response.Status.BAD_REQUEST);\n}\n+ // https://tools.ietf.org/html/rfc7636#section-4.6\n+ String codeVerifier = formParams.getFirst(OAuth2Constants.CODE_VERIFIER);\n+ String codeChallenge = deviceCodeModel.getCodeChallenge();\n+ String codeChallengeMethod = deviceCodeModel.getCodeChallengeMethod();\n+\n+ if (codeChallengeMethod != null && !codeChallengeMethod.isEmpty()) {\n+ PkceUtils.checkParamsForPkceEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, null, null, event, cors);\n+ } else {\n+ // PKCE Activation is OFF, execute the codes implemented in KEYCLOAK-2604\n+ PkceUtils.checkParamsForPkceNotEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, null, null, event, cors);\n+ }\n+\n// Approved\nString userSessionId = deviceCodeModel.getUserSessionId();\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/device/endpoints/DeviceEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/device/endpoints/DeviceEndpoint.java", "diff": "@@ -37,6 +37,7 @@ import org.keycloak.models.OAuth2DeviceUserCodeProvider;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.protocol.AuthorizationEndpointBase;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\n+import org.keycloak.protocol.oidc.endpoints.AuthorizationEndpointChecker;\nimport org.keycloak.protocol.oidc.endpoints.request.AuthorizationEndpointRequest;\nimport org.keycloak.protocol.oidc.endpoints.request.AuthorizationEndpointRequestParserProcessor;\nimport org.keycloak.protocol.oidc.grants.device.DeviceGrantType;\n@@ -123,6 +124,18 @@ public class DeviceEndpoint extends AuthorizationEndpointBase implements RealmRe\n\"Client not allowed for OAuth 2.0 Device Authorization Grant\", Response.Status.BAD_REQUEST);\n}\n+ // https://tools.ietf.org/html/rfc7636#section-4\n+ AuthorizationEndpointChecker checker = new AuthorizationEndpointChecker()\n+ .event(event)\n+ .client(client)\n+ .request(request);\n+\n+ try {\n+ checker.checkPKCEParams();\n+ } catch (AuthorizationEndpointChecker.AuthorizationCheckException ex) {\n+ throw new ErrorResponseException(ex.getError(), ex.getErrorDescription(), Response.Status.BAD_REQUEST);\n+ }\n+\ntry {\nsession.clientPolicy().triggerOnEvent(new DeviceAuthorizationRequestContext(request, httpRequest.getDecodedFormParameters()));\n} catch (ClientPolicyException cpe) {\n@@ -134,7 +147,7 @@ public class DeviceEndpoint extends AuthorizationEndpointBase implements RealmRe\nOAuth2DeviceCodeModel deviceCode = OAuth2DeviceCodeModel.create(realm, client,\nBase64Url.encode(SecretGenerator.getInstance().randomBytes()), request.getScope(), request.getNonce(), expiresIn, interval, null, null,\n- request.getAdditionalReqParams());\n+ request.getAdditionalReqParams(), request.getCodeChallenge(), request.getCodeChallengeMethod());\nOAuth2DeviceUserCodeProvider userCodeProvider = session.getProvider(OAuth2DeviceUserCodeProvider.class);\nString secret = userCodeProvider.generate();\nOAuth2DeviceUserCodeModel userCode = new OAuth2DeviceUserCodeModel(realm, deviceCode.getDeviceCode(), secret);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/PkceUtils.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/PkceUtils.java", "diff": "package org.keycloak.protocol.oidc.utils;\n+import org.jboss.logging.Logger;\nimport org.keycloak.OAuth2Constants;\n+import org.keycloak.OAuthErrorException;\nimport org.keycloak.common.util.Base64Url;\nimport org.keycloak.common.util.SecretGenerator;\n+import org.keycloak.events.Errors;\n+import org.keycloak.protocol.oidc.OIDCLoginProtocol;\n+import org.keycloak.services.CorsErrorResponseException;\n+import org.keycloak.events.EventBuilder;\n+import org.keycloak.services.resources.Cors;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\n+import java.util.regex.Matcher;\n+import java.util.regex.Pattern;\n+\n+import javax.ws.rs.core.Response;\npublic class PkceUtils {\n+ private static final Logger logger = Logger.getLogger(PkceUtils.class);\n+\n+ private static final Pattern VALID_CODE_VERIFIER_PATTERN = Pattern.compile(\"^[0-9a-zA-Z\\\\-\\\\.~_]+$\");\n+\npublic static String generateCodeVerifier() {\nreturn Base64Url.encode(SecretGenerator.getInstance().randomBytes(64));\n}\n@@ -51,4 +66,74 @@ public class PkceUtils {\nreturn false;\n}\n}\n+\n+ public static void checkParamsForPkceEnforcedClient(String codeVerifier, String codeChallenge, String codeChallengeMethod, String authUserId, String authUsername, EventBuilder event, Cors cors) {\n+ // check whether code verifier is specified\n+ if (codeVerifier == null) {\n+ logger.warnf(\"PKCE code verifier not specified, authUserId = %s, authUsername = %s\", authUserId, authUsername);\n+ event.error(Errors.CODE_VERIFIER_MISSING);\n+ throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE code verifier not specified\", Response.Status.BAD_REQUEST);\n+ }\n+ verifyCodeVerifier(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);\n+ }\n+\n+ public static void checkParamsForPkceNotEnforcedClient(String codeVerifier, String codeChallenge, String codeChallengeMethod, String authUserId, String authUsername, EventBuilder event, Cors cors) {\n+ if (codeChallenge != null && codeVerifier == null) {\n+ logger.warnf(\"PKCE code verifier not specified, authUserId = %s, authUsername = %s\", authUserId, authUsername);\n+ event.error(Errors.CODE_VERIFIER_MISSING);\n+ throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE code verifier not specified\", Response.Status.BAD_REQUEST);\n+ }\n+\n+ if (codeChallenge != null) {\n+ verifyCodeVerifier(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);\n+ }\n+ }\n+\n+ public static void verifyCodeVerifier(String codeVerifier, String codeChallenge, String codeChallengeMethod, String authUserId, String authUsername, EventBuilder event, Cors cors) {\n+ // check whether code verifier is formatted along with the PKCE specification\n+\n+ if (!isValidPkceCodeVerifier(codeVerifier)) {\n+ logger.infof(\"PKCE invalid code verifier\");\n+ event.error(Errors.INVALID_CODE_VERIFIER);\n+ throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE invalid code verifier\", Response.Status.BAD_REQUEST);\n+ }\n+\n+ logger.debugf(\"PKCE supporting Client, codeVerifier = %s\", codeVerifier);\n+ String codeVerifierEncoded = codeVerifier;\n+ try {\n+ // https://tools.ietf.org/html/rfc7636#section-4.2\n+ // plain or S256\n+ if (codeChallengeMethod != null && codeChallengeMethod.equals(OAuth2Constants.PKCE_METHOD_S256)) {\n+ logger.debugf(\"PKCE codeChallengeMethod = %s\", codeChallengeMethod);\n+ codeVerifierEncoded = PkceUtils.generateS256CodeChallenge(codeVerifier);\n+ } else {\n+ logger.debug(\"PKCE codeChallengeMethod is plain\");\n+ codeVerifierEncoded = codeVerifier;\n+ }\n+ } catch (Exception nae) {\n+ logger.infof(\"PKCE code verification failed, not supported algorithm specified\");\n+ event.error(Errors.PKCE_VERIFICATION_FAILED);\n+ throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE code verification failed, not supported algorithm specified\", Response.Status.BAD_REQUEST);\n+ }\n+ if (!codeChallenge.equals(codeVerifierEncoded)) {\n+ logger.warnf(\"PKCE verification failed. authUserId = %s, authUsername = %s\", authUserId, authUsername);\n+ event.error(Errors.PKCE_VERIFICATION_FAILED);\n+ throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, \"PKCE verification failed\", Response.Status.BAD_REQUEST);\n+ } else {\n+ logger.debugf(\"PKCE verification success. codeVerifierEncoded = %s, codeChallenge = %s\", codeVerifierEncoded, codeChallenge);\n+ }\n+ }\n+\n+ private static boolean isValidPkceCodeVerifier(String codeVerifier) {\n+ if (codeVerifier.length() < OIDCLoginProtocol.PKCE_CODE_VERIFIER_MIN_LENGTH) {\n+ logger.infof(\" Error: PKCE codeVerifier length under lower limit , codeVerifier = %s\", codeVerifier);\n+ return false;\n+ }\n+ if (codeVerifier.length() > OIDCLoginProtocol.PKCE_CODE_VERIFIER_MAX_LENGTH) {\n+ logger.infof(\" Error: PKCE codeVerifier length over upper limit , codeVerifier = %s\", codeVerifier);\n+ return false;\n+ }\n+ Matcher m = VALID_CODE_VERIFIER_PATTERN.matcher(codeVerifier);\n+ return m.matches();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/OAuthClient.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/OAuthClient.java", "diff": "@@ -1004,6 +1004,12 @@ public class OAuthClient {\nif (nonce != null) {\nparameters.add(new BasicNameValuePair(OIDCLoginProtocol.NONCE_PARAM, scope));\n}\n+ if (codeChallenge != null) {\n+ parameters.add(new BasicNameValuePair(OAuth2Constants.CODE_CHALLENGE, codeChallenge));\n+ }\n+ if (codeChallengeMethod != null) {\n+ parameters.add(new BasicNameValuePair(OAuth2Constants.CODE_CHALLENGE_METHOD, codeChallengeMethod));\n+ }\nUrlEncodedFormEntity formEntity;\ntry {\n@@ -1034,6 +1040,10 @@ public class OAuthClient {\nif (origin != null) {\npost.addHeader(\"Origin\", origin);\n}\n+ // https://tools.ietf.org/html/rfc7636#section-4.5\n+ if (codeVerifier != null) {\n+ parameters.add(new BasicNameValuePair(OAuth2Constants.CODE_VERIFIER, codeVerifier));\n+ }\nUrlEncodedFormEntity formEntity;\ntry {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2DeviceAuthorizationGrantTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2DeviceAuthorizationGrantTest.java", "diff": "@@ -25,6 +25,7 @@ import org.jboss.arquillian.graphene.page.Page;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.keycloak.OAuth2Constants;\nimport org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.models.ClientScopeModel;\n@@ -41,6 +42,7 @@ import org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.AssertEvents;\nimport org.keycloak.testsuite.admin.ApiUtil;\n+import org.keycloak.testsuite.oidc.PkceGenerator;\nimport org.keycloak.testsuite.pages.ErrorPage;\nimport org.keycloak.testsuite.pages.OAuth2DeviceVerificationPage;\nimport org.keycloak.testsuite.pages.OAuthGrantPage;\n@@ -254,6 +256,81 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {\nAssert.assertEquals(\"211211211\", userInfo.getPhoneNumber());\n}\n+ @Test\n+ public void testPublicClientWithPKCESuccess() throws Exception {\n+ // Successful Device Authorization Request with PKCE from device\n+ oauth.realm(REALM_NAME);\n+ oauth.clientId(DEVICE_APP_PUBLIC);\n+ PkceGenerator pkce = new PkceGenerator();\n+ oauth.codeChallenge(pkce.getCodeChallenge());\n+ oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_S256);\n+ oauth.codeVerifier(pkce.getCodeVerifier());\n+ OAuthClient.DeviceAuthorizationResponse response = oauth.doDeviceAuthorizationRequest(DEVICE_APP_PUBLIC, null);\n+\n+ Assert.assertEquals(200, response.getStatusCode());\n+ assertNotNull(response.getDeviceCode());\n+ assertNotNull(response.getUserCode());\n+ assertNotNull(response.getVerificationUri());\n+ assertNotNull(response.getVerificationUriComplete());\n+ Assert.assertEquals(60, response.getExpiresIn());\n+ Assert.assertEquals(5, response.getInterval());\n+\n+ openVerificationPage(response.getVerificationUriComplete());\n+\n+ // Do Login\n+ oauth.fillLoginForm(\"device-login\", \"password\");\n+\n+ // Consent\n+ grantPage.accept();\n+\n+ // Token request from device\n+ OAuthClient.AccessTokenResponse tokenResponse = oauth.doDeviceTokenRequest(DEVICE_APP_PUBLIC, null, response.getDeviceCode());\n+\n+ Assert.assertEquals(200, tokenResponse.getStatusCode());\n+\n+ String tokenString = tokenResponse.getAccessToken();\n+ assertNotNull(tokenString);\n+ AccessToken token = oauth.verifyToken(tokenString);\n+\n+ assertNotNull(token);\n+ }\n+\n+ @Test\n+ public void testPublicClientWithPKCEFail() throws Exception {\n+ // Device Authorization Request with PKCE from device - device send false code_verifier\n+ oauth.realm(REALM_NAME);\n+ oauth.clientId(DEVICE_APP_PUBLIC);\n+ PkceGenerator pkce = new PkceGenerator();\n+ oauth.codeChallenge(pkce.getCodeChallenge());\n+ oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_S256);\n+ oauth.codeVerifier(pkce.getCodeVerifier()+\"a\");\n+ OAuthClient.DeviceAuthorizationResponse response = oauth.doDeviceAuthorizationRequest(DEVICE_APP_PUBLIC, null);\n+\n+ Assert.assertEquals(200, response.getStatusCode());\n+ assertNotNull(response.getDeviceCode());\n+ assertNotNull(response.getUserCode());\n+ assertNotNull(response.getVerificationUri());\n+ assertNotNull(response.getVerificationUriComplete());\n+ Assert.assertEquals(60, response.getExpiresIn());\n+ Assert.assertEquals(5, response.getInterval());\n+\n+ openVerificationPage(response.getVerificationUriComplete());\n+\n+ // Do Login\n+ oauth.fillLoginForm(\"device-login\", \"password\");\n+\n+ // Consent\n+ grantPage.accept();\n+\n+ // Token request from device\n+ OAuthClient.AccessTokenResponse tokenResponse = oauth.doDeviceTokenRequest(DEVICE_APP_PUBLIC, null, response.getDeviceCode());\n+\n+ Assert.assertEquals(400, tokenResponse.getStatusCode());\n+ Assert.assertEquals(\"invalid_grant\", tokenResponse.getError());\n+ Assert.assertEquals(\"PKCE verification failed\", tokenResponse.getErrorDescription());\n+ }\n+\n+\n@Test\npublic void testPublicClientCustomConsent() throws Exception {\n// Device Authorization Request from device\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Device Authorization Grant with PKCE Closes #9710
339,391
03.02.2022 09:38:45
-3,600
3fd725a3f5dfbe4f380383c088b0beed66a3ef80
Test Baseline Closes
[ { "change_type": "MODIFY", "old_path": ".github/workflows/operator-ci.yml", "new_path": ".github/workflows/operator-ci.yml", "diff": "@@ -34,6 +34,18 @@ jobs:\nrun: |\nmvn clean install -DskipTests -DskipExamples -DskipTestsuite\n- - name: Build the Keycloak Operator\n+ - name: Setup Minikube-Kubernetes\n+ uses: manusa/[email protected]\n+ with:\n+ minikube version: v1.24.0\n+ kubernetes version: v1.22.3\n+ github token: ${{ secrets.GITHUB_TOKEN }}\n+ driver: docker\n+ - name: Build , deploy and test operator in minikube\nrun: |\n- mvn clean package -nsu -B -e -pl operator -Doperator -Dquarkus.container-image.build=true -Dquarkus.kubernetes.deployment-target=minikube\n+ cd operator\n+ eval $(minikube -p minikube docker-env)\n+ mvn clean verify \\\n+ -Dquarkus.container-image.build=true -Dquarkus.container-image.tag=test \\\n+ -Dquarkus.kubernetes.deployment-target=kubernetes \\\n+ --no-transfer-progress -Dtest.operator.deployment=remote\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "operator/pom.xml", "new_path": "operator/pom.xml", "diff": "<maven.compiler.target>11</maven.compiler.target>\n<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n- <quarkus.operator.sdk.version>3.0.0-SNAPSHOT</quarkus.operator.sdk.version>\n+ <quarkus.operator.sdk.version>3.0.2</quarkus.operator.sdk.version>\n<quarkus.version>2.6.1.Final</quarkus.version>\n<quarkus.container-image.group>keycloak</quarkus.container-image.group>\n<quarkus.jib.base-jvm-image>eclipse-temurin:11</quarkus.jib.base-jvm-image>\n<quarkus.kubernetes.image-pull-policy>Never</quarkus.kubernetes.image-pull-policy>\n+ <maven-failsafe-plugin.version>2.22.0</maven-failsafe-plugin.version>\n</properties>\n<repositories>\n<groupId>org.keycloak</groupId>\n<artifactId>keycloak-common</artifactId>\n</dependency>\n+\n+ <!-- Test -->\n+ <dependency>\n+ <groupId>io.quarkus</groupId>\n+ <artifactId>quarkus-test-common</artifactId>\n+ <scope>test</scope>\n+ </dependency>\n+ <dependency>\n+ <groupId>io.quarkus</groupId>\n+ <artifactId>quarkus-junit5</artifactId>\n+ <scope>test</scope>\n+ </dependency>\n+ <dependency>\n+ <groupId>org.assertj</groupId>\n+ <artifactId>assertj-core</artifactId>\n+ <version>${assertj-core.version}</version>\n+ <scope>test</scope>\n+ </dependency>\n+ <dependency>\n+ <groupId>org.awaitility</groupId>\n+ <artifactId>awaitility</artifactId>\n+ <version>${awaitility.version}</version>\n+ <scope>test</scope>\n+ </dependency>\n</dependencies>\n<build>\n</execution>\n</executions>\n</plugin>\n-\n+ <plugin>\n+ <artifactId>maven-failsafe-plugin</artifactId>\n+ <version>${maven-failsafe-plugin.version}</version>\n+ <executions>\n+ <execution>\n+ <goals>\n+ <goal>integration-test</goal>\n+ <goal>verify</goal>\n+ </goals>\n+ </execution>\n+ </executions>\n+ </plugin>\n</plugins>\n</build>\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/Constants.java", "new_path": "operator/src/main/java/org/keycloak/operator/Constants.java", "diff": "@@ -33,6 +33,6 @@ public final class Constants {\n);\npublic static final Map<String, String> DEFAULT_DIST_CONFIG = Map.of(\n- \"KEYCLOAK_METRICS_ENABLED\", \"true\"\n+ \"KC_METRICS_ENABLED\", \"true\"\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/KeycloakController.java", "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/KeycloakController.java", "diff": "@@ -18,7 +18,6 @@ package org.keycloak.operator.v2alpha1;\nimport javax.inject.Inject;\n-import io.fabric8.kubernetes.api.model.OwnerReference;\nimport io.fabric8.kubernetes.api.model.apps.Deployment;\nimport io.fabric8.kubernetes.client.KubernetesClient;\nimport io.fabric8.kubernetes.client.informers.SharedIndexInformer;\n@@ -30,9 +29,9 @@ import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer;\nimport io.javaoperatorsdk.operator.api.reconciler.Reconciler;\nimport io.javaoperatorsdk.operator.api.reconciler.RetryInfo;\nimport io.javaoperatorsdk.operator.api.reconciler.UpdateControl;\n-import io.javaoperatorsdk.operator.processing.event.ResourceID;\nimport io.javaoperatorsdk.operator.processing.event.source.EventSource;\nimport io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource;\n+import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers;\nimport io.quarkus.logging.Log;\nimport org.keycloak.operator.Config;\nimport org.keycloak.operator.Constants;\n@@ -43,11 +42,11 @@ import org.keycloak.operator.v2alpha1.crds.KeycloakStatusBuilder;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\n-import java.util.Set;\n+import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_FINALIZER;\nimport static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE;\n-@ControllerConfiguration(namespaces = WATCH_CURRENT_NAMESPACE)\n+@ControllerConfiguration(namespaces = WATCH_CURRENT_NAMESPACE, finalizerName = NO_FINALIZER)\npublic class KeycloakController implements Reconciler<Keycloak>, EventSourceInitializer<Keycloak>, ErrorStatusHandler<Keycloak> {\n@Inject\n@@ -59,19 +58,11 @@ public class KeycloakController implements Reconciler<Keycloak>, EventSourceInit\n@Override\npublic List<EventSource> prepareEventSources(EventSourceContext<Keycloak> context) {\nSharedIndexInformer<Deployment> deploymentInformer =\n- client.apps().deployments().inAnyNamespace()\n+ client.apps().deployments().inNamespace(context.getConfigurationService().getClientConfiguration().getNamespace())\n.withLabels(Constants.DEFAULT_LABELS)\n.runnableInformer(0);\n- EventSource deploymentEvent = new InformerEventSource<>(\n- deploymentInformer, d -> {\n- List<OwnerReference> ownerReferences = d.getMetadata().getOwnerReferences();\n- if (!ownerReferences.isEmpty()) {\n- return Set.of(new ResourceID(ownerReferences.get(0).getName(), d.getMetadata().getNamespace()));\n- } else {\n- return Collections.emptySet();\n- }\n- });\n+ EventSource deploymentEvent = new InformerEventSource<>(deploymentInformer, Mappers.fromOwnerReference());\nreturn List.of(deploymentEvent);\n}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/Keycloak.java", "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/Keycloak.java", "diff": "@@ -22,12 +22,20 @@ import io.fabric8.kubernetes.model.annotation.Group;\nimport io.fabric8.kubernetes.model.annotation.Plural;\nimport io.fabric8.kubernetes.model.annotation.ShortNames;\nimport io.fabric8.kubernetes.model.annotation.Version;\n+import io.sundr.builder.annotations.Buildable;\n+import io.sundr.builder.annotations.BuildableReference;\nimport org.keycloak.operator.Constants;\n@Group(Constants.CRDS_GROUP)\n@Version(Constants.CRDS_VERSION)\n@ShortNames(Constants.SHORT_NAME)\n@Plural(Constants.PLURAL_NAME)\n+@Buildable(editableEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\",\n+ lazyCollectionInitEnabled = false, refs = {\n+ @BuildableReference(io.fabric8.kubernetes.api.model.ObjectMeta.class),\n+ @BuildableReference(io.fabric8.kubernetes.client.CustomResource.class),\n+ @BuildableReference(org.keycloak.operator.v2alpha1.crds.KeycloakSpec.class)\n+})\npublic class Keycloak extends CustomResource<KeycloakSpec, KeycloakStatus> implements Namespaced {\n}\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakSpec.java", "new_path": "operator/src/main/java/org/keycloak/operator/v2alpha1/crds/KeycloakSpec.java", "diff": "*/\npackage org.keycloak.operator.v2alpha1.crds;\n-import io.fabric8.kubernetes.api.model.PodTemplate;\n-\nimport java.util.Map;\npublic class KeycloakSpec {\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/resources/base-keycloak-deployment.yaml", "new_path": "operator/src/main/resources/base-keycloak-deployment.yaml", "diff": "@@ -27,16 +27,19 @@ spec:\n- containerPort: 8080\nprotocol: TCP\nlivenessProbe:\n- exec:\n- command:\n- - curl --head --fail --silent http://127.0.0.1:8080/health/live\n- periodSeconds: 1\n+ httpGet:\n+ path: /health/live\n+ port: 8080\n+ initialDelaySeconds: 15\n+ periodSeconds: 2\n+ failureThreshold: 10\nreadinessProbe:\n- exec:\n- command:\n- - curl --head --fail --silent http://127.0.0.1:8080/health/ready\n- periodSeconds: 1\n- failureThreshold: 180\n+ httpGet:\n+ path: /health/ready\n+ port: 8080\n+ initialDelaySeconds: 15\n+ periodSeconds: 2\n+ failureThreshold: 10\ndnsPolicy: ClusterFirst\nrestartPolicy: Always\nterminationGracePeriodSeconds: 30\n" }, { "change_type": "MODIFY", "old_path": "operator/src/main/resources/example-keycloak.yml", "new_path": "operator/src/main/resources/example-keycloak.yml", "diff": "@@ -4,7 +4,7 @@ metadata:\nname: example-kc\nspec:\ninstances: 1\n- distConfig:\n+ serverConfiguration:\nKC_DB: postgres\nKC_DB_URL_HOST: postgres-db\n# KC_DB_USERNAME: ${secret:keycloak-db-secret:username}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/test/java/org/keycloak/operator/ClusterOperatorTest.java", "diff": "+package org.keycloak.operator;\n+\n+import io.fabric8.kubernetes.api.model.HasMetadata;\n+import io.fabric8.kubernetes.api.model.NamespaceBuilder;\n+import io.fabric8.kubernetes.api.model.apps.Deployment;\n+import io.fabric8.kubernetes.client.Config;\n+import io.fabric8.kubernetes.client.ConfigBuilder;\n+import io.fabric8.kubernetes.client.DefaultKubernetesClient;\n+import io.fabric8.kubernetes.client.KubernetesClient;\n+import io.javaoperatorsdk.operator.Operator;\n+import io.javaoperatorsdk.operator.api.reconciler.Reconciler;\n+import io.quarkiverse.operatorsdk.runtime.OperatorProducer;\n+import io.quarkiverse.operatorsdk.runtime.QuarkusConfigurationService;\n+import io.quarkus.logging.Log;\n+import org.eclipse.microprofile.config.ConfigProvider;\n+import org.junit.jupiter.api.AfterAll;\n+import org.junit.jupiter.api.BeforeAll;\n+\n+import javax.enterprise.inject.Instance;\n+import javax.enterprise.inject.spi.CDI;\n+import javax.enterprise.util.TypeLiteral;\n+import java.io.FileInputStream;\n+import java.io.FileNotFoundException;\n+import java.util.List;\n+import java.util.UUID;\n+\n+import static org.assertj.core.api.Assertions.assertThat;\n+\n+public abstract class ClusterOperatorTest {\n+\n+ public static final String QUARKUS_KUBERNETES_DEPLOYMENT_TARGET = \"quarkus.kubernetes.deployment-target\";\n+ public static final String OPERATOR_DEPLOYMENT_PROP = \"test.operator.deployment\";\n+ public static final String TARGET_KUBERNETES_GENERATED_YML_FOLDER = \"target/kubernetes/\";\n+\n+ public enum OperatorDeployment {local,remote}\n+\n+ protected static OperatorDeployment operatorDeployment;\n+ protected static Instance<Reconciler<? extends HasMetadata>> reconcilers;\n+ protected static QuarkusConfigurationService configuration;\n+ protected static KubernetesClient k8sclient;\n+ protected static String namespace;\n+ protected static String deploymentTarget;\n+ private static Operator operator;\n+\n+\n+ @BeforeAll\n+ public static void before() throws FileNotFoundException {\n+ configuration = CDI.current().select(QuarkusConfigurationService.class).get();\n+ reconcilers = CDI.current().select(new TypeLiteral<>() {});\n+ operatorDeployment = ConfigProvider.getConfig().getOptionalValue(OPERATOR_DEPLOYMENT_PROP, OperatorDeployment.class).orElse(OperatorDeployment.local);\n+ deploymentTarget = ConfigProvider.getConfig().getOptionalValue(QUARKUS_KUBERNETES_DEPLOYMENT_TARGET, String.class).orElse(\"kubernetes\");\n+\n+ calculateNamespace();\n+ createK8sClient();\n+ createNamespace();\n+\n+ if (operatorDeployment == OperatorDeployment.remote) {\n+ createCRD();\n+ createRBACresourcesAndOperatorDeployment();\n+ } else {\n+ createOperator();\n+ registerReconcilers();\n+ operator.start();\n+ }\n+\n+ }\n+\n+ private static void createK8sClient() {\n+ k8sclient = new DefaultKubernetesClient(new ConfigBuilder(Config.autoConfigure(null)).withNamespace(namespace).build());\n+ }\n+\n+ private static void createRBACresourcesAndOperatorDeployment() throws FileNotFoundException {\n+ Log.info(\"Creating RBAC into Namespace \" + namespace);\n+ List<HasMetadata> hasMetadata = k8sclient.load(new FileInputStream(TARGET_KUBERNETES_GENERATED_YML_FOLDER + deploymentTarget + \".yml\"))\n+ .inNamespace(namespace).get();\n+ hasMetadata.stream()\n+ .map(b -> {\n+ if (\"Deployment\".equalsIgnoreCase(b.getKind()) && b.getMetadata().getName().contains(\"operator\")) {\n+ ((Deployment) b).getSpec().getTemplate().getSpec().getContainers().get(0).setImagePullPolicy(\"Never\");\n+ }\n+ return b;\n+ }).forEach(c -> {\n+ Log.info(\"processing part : \" + c.getKind() + \"--\" + c.getMetadata().getName() + \" -- \" + namespace);\n+ k8sclient.resource(c).inNamespace(namespace).createOrReplace();\n+ });\n+ }\n+\n+ private static void cleanRBACresourcesAndOperatorDeployment() throws FileNotFoundException {\n+ Log.info(\"Deleting RBAC from Namespace \" + namespace);\n+ k8sclient.load(new FileInputStream(TARGET_KUBERNETES_GENERATED_YML_FOLDER +deploymentTarget+\".yml\"))\n+ .inNamespace(namespace).delete();\n+ }\n+ private static void createCRD() throws FileNotFoundException {\n+ Log.info(\"Creating CRD \");\n+ k8sclient.load(new FileInputStream(TARGET_KUBERNETES_GENERATED_YML_FOLDER + \"keycloaks.keycloak.org-v1.yml\")).createOrReplace();\n+ }\n+\n+ private static void registerReconcilers() {\n+ Log.info(\"Registering reconcilers for operator : \" + operator + \" [\" + operatorDeployment + \"]\");\n+\n+ for (Reconciler reconciler : reconcilers) {\n+ final var config = configuration.getConfigurationFor(reconciler);\n+ if (!config.isRegistrationDelayed()) {\n+ Log.info(\"Register and apply : \" + reconciler.getClass().getName());\n+ OperatorProducer.applyCRDIfNeededAndRegister(operator, reconciler, configuration);\n+ }\n+ }\n+ }\n+\n+ private static void createOperator() {\n+ operator = new Operator(k8sclient, configuration);\n+ operator.getConfigurationService().getClientConfiguration().setNamespace(namespace);\n+ }\n+\n+ private static void createNamespace() {\n+ Log.info(\"Creating Namespace \" + namespace);\n+ k8sclient.namespaces().create(new NamespaceBuilder().withNewMetadata().withName(namespace).endMetadata().build());\n+ }\n+\n+ private static void calculateNamespace() {\n+ namespace = \"keycloak-test-\" + UUID.randomUUID();\n+ }\n+\n+ @AfterAll\n+ public static void after() throws FileNotFoundException {\n+\n+ if (operatorDeployment == OperatorDeployment.local) {\n+ Log.info(\"Stopping Operator\");\n+ operator.stop();\n+\n+ Log.info(\"Creating new K8s Client\");\n+ // create a new client bc operator has closed the old one\n+ createK8sClient();\n+ } else {\n+ cleanRBACresourcesAndOperatorDeployment();\n+ }\n+\n+ Log.info(\"Deleting namespace : \" + namespace);\n+ assertThat(k8sclient.namespaces().withName(namespace).delete()).isTrue();\n+ k8sclient.close();\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/test/java/org/keycloak/operator/OperatorE2EIT.java", "diff": "+package org.keycloak.operator;\n+\n+import io.quarkus.logging.Log;\n+import io.quarkus.test.junit.QuarkusTest;\n+import org.awaitility.Awaitility;\n+import org.awaitility.core.ConditionTimeoutException;\n+import org.junit.jupiter.api.Test;\n+\n+import java.io.IOException;\n+import java.time.Duration;\n+\n+import static org.assertj.core.api.Assertions.assertThat;\n+\n+@QuarkusTest\n+public class OperatorE2EIT extends ClusterOperatorTest {\n+ @Test\n+ public void given_ClusterAndOperatorRunning_when_KeycloakCRCreated_Then_KeycloakStructureIsDeployedAndStatusIsOK() throws IOException {\n+ Log.info(((operatorDeployment == OperatorDeployment.remote) ? \"Remote \" : \"Local \") + \"Run Test :\" + namespace);\n+\n+ // DB\n+ Log.info(\"Creating new PostgreSQL deployment\");\n+ k8sclient.load(OperatorE2EIT.class.getResourceAsStream(\"/example-postgres.yaml\")).inNamespace(namespace).createOrReplace();\n+\n+ // Check DB has deployed and ready\n+ Log.info(\"Checking Postgres is running\");\n+ Awaitility.await()\n+ .atMost(Duration.ofSeconds(60))\n+ .pollDelay(Duration.ofSeconds(2))\n+ .untilAsserted(() -> assertThat(k8sclient.apps().statefulSets().inNamespace(namespace).withName(\"postgresql-db\").get().getStatus().getReadyReplicas()).isEqualTo(1));\n+ // CR\n+ Log.info(\"Creating new Keycloak CR example\");\n+ k8sclient.load(OperatorE2EIT.class.getResourceAsStream(\"/example-keycloak.yml\")).inNamespace(namespace).createOrReplace();\n+\n+ // Check Operator has deployed Keycloak\n+ Log.info(\"Checking Operator has deployed Keycloak deployment\");\n+ Awaitility.await()\n+ .atMost(Duration.ofSeconds(60))\n+ .pollDelay(Duration.ofSeconds(2))\n+ .untilAsserted(() -> assertThat(k8sclient.apps().deployments().inNamespace(namespace).withName(\"example-kc\").get()).isNotNull());\n+\n+ // Check Keycloak has status ready\n+ StringBuffer podlog = new StringBuffer();\n+ try {\n+ Log.info(\"Checking Keycloak pod has ready replicas == 1\");\n+ Awaitility.await()\n+ .atMost(Duration.ofSeconds(180))\n+ .pollDelay(Duration.ofSeconds(5))\n+ .untilAsserted(() -> {\n+ podlog.delete(0, podlog.length());\n+ try {\n+ k8sclient.pods().inNamespace(namespace).list().getItems().stream()\n+ .filter(a -> a.getMetadata().getName().startsWith(\"example-kc\"))\n+ .forEach(a -> podlog.append(a.getMetadata().getName()).append(\" : \")\n+ .append(k8sclient.pods().inNamespace(namespace).withName(a.getMetadata().getName()).getLog(true)));\n+ } catch (Exception e) {\n+ // swallowing exception bc the pod is not ready to give logs yet\n+ }\n+ assertThat(k8sclient.apps().deployments().inNamespace(namespace).withName(\"example-kc\").get().getStatus().getReadyReplicas()).isEqualTo(1);\n+ });\n+ } catch (ConditionTimeoutException e) {\n+ Log.error(\"On error POD LOG \" + podlog, e);\n+ throw e;\n+ }\n+\n+\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<selenium.version>2.35.0</selenium.version>\n<xml-apis.version>1.4.01</xml-apis.version>\n<subethasmtp.version>3.1.7</subethasmtp.version>\n+ <awaitility.version>4.1.1</awaitility.version>\n+ <assertj-core.version>3.22.0</assertj-core.version>\n<!-- KEYCLOAK-17585 Prevent microprofile-metrics-api upgrades from version \"2.3\" due to:\nhttps://issues.redhat.com/browse/KEYCLOAK-17585?focusedCommentId=16002705&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-16002705\n-->\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Test Baseline (#9625) Closes #9174 Signed-off-by: jonathan <[email protected]>
339,181
03.02.2022 03:55:07
18,000
c5e95b1dbae134aaa21a4158f60f4f1fd8fcd23f
9954 Review vault topic
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/vault.adoc", "new_path": "docs/guides/src/main/server/vault.adoc", "diff": "<@tmpl.guide\ntitle=\"Using Kubernetes Secrets\"\nsummary=\"Learn how to use Kubernetes/OpenShift secrets in Keycloak\"\n+priority=30\nincludedOptions=\"vault vault-*\">\n-Keycloak supports a file based vault implementation for Kubernetes / OpenShift secrets. Mount Kubernetes secrets into the Keycloak Container, and the data fields will be available in the mounted folder with a flat-file structure.\n+Keycloak supports a file-based vault implementation for Kubernetes/OpenShift secrets. Mount Kubernetes secrets into the Keycloak Container, and the data fields will be available in the mounted folder with a flat-file structure.\n== Available integrations\n-You can use Kubernetes / OpenShift secrets for the following use-cases:\n+You can use Kubernetes/OpenShift secrets for the following purposes:\n* Obtain the SMTP Mail server Password\n* Obtain the LDAP Bind Credential when using LDAP-based User Federation\n@@ -21,19 +22,19 @@ Enable the file based vault by building Keycloak using the following build optio\n<@kc.build parameters=\"--vault=file\"/>\n== Setting the base directory to lookup secrets\n-Kubernetes / OpenShift secrets are basically mounted files, so you have to configure a directory for these files to be mounted in:\n+Kubernetes/OpenShift secrets are basically mounted files. To configure a directory where these files should be mounted, enter this command:\n<@kc.start parameters=\"--vault-dir=/my/path\"/>\n== Realm-specific secret files\n-Kubernetes / OpenShift Secrets are used per-realm basis in Keycloak, so there's a naming convention for the file in place:\n+Kubernetes/OpenShift Secrets are used on a per-realm basis in Keycloak, which requires a naming convention for the file in place:\n[source, bash]\n----\n${r\"${vault.<realmname>_<secretname>}\"}\n----\n=== Using underscores in the Name\n-In order to process the secret correctly, it is needed to double all underscores in the <realmname> or the <secretname>, separated by a single underscore.\n+To process the secret correctly, you double all underscores in the <realmname> or the <secretname>, separated by a single underscore.\n.Example\n* Realm Name: `sso_realm`\n@@ -45,14 +46,14 @@ sso__realm_ldap__credential\n----\nNote the doubled underscores between __sso__ and __realm__ and also between __ldap__ and __credential__.\n-== Example: Use an LDAP bind credential secret in the admin console\n+== Example: Use an LDAP bind credential secret in the Admin Console\n.Example setup\n* A realm named `secrettest`\n* A desired Name `ldapBc` for the bind Credential\n* Resulting file name: `secrettest_ldapBc`\n-.Usage in admin console\n-You can then use this secret from the admin console by using `${r\"${vault.ldapBc}\"}` as value for the `Bind Credential` when configuring your LDAP User federation.\n+.Usage in Admin Console\n+You can then use this secret from the Admin Console by using `${r\"${vault.ldapBc}\"}` as the value for the `Bind Credential` when configuring your LDAP User federation.\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
9954 Review vault topic (#9955)
339,618
03.02.2022 13:42:46
-3,600
9cb0cc8f8ab3bc0a177d1b77599528bfad10ecc2
Configure Caching Guide V1 * Configure Caching Guide V1 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/guides/src/main/server/caching.adoc", "diff": "+<#import \"/templates/guide.adoc\" as tmpl>\n+<#import \"/templates/kc.adoc\" as kc>\n+<#import \"/templates/options.adoc\" as opts>\n+\n+<@tmpl.guide\n+title=\"Configure distributed caches\"\n+summary=\"Understand how to configure the caching layer\"\n+includedOptions=\"cache cache-*\">\n+\n+Keycloak is designed for high availability and multi-node clustered setups. The current distributed cache implementation is built on top of https://infinispan.org[Infinispan], a high-performance, distributable in-memory data grid.\n+\n+All available cache options are build options, so they need to be applied to a `build` of Keycloak before starting.\n+\n+== Enable distributed caching\n+Caching is enabled per default when you start Keycloak in production mode, using the `start` command. This will automatically discover other Keycloak nodes in your network. To explicitly enable distributed infinispan caching, use:\n+\n+<@kc.build parameters=\"--cache=ispn\"/>\n+\n+When you start Keycloak in development mode, using the `start-dev` command, Keycloak defaults to only use local caches using `--cache=local` instead. Using the `local` cache mode is intended only for development and testing purposes.\n+\n+== Configure Caches\n+Keycloak provides a cache configuration file with sensible defaults located at `conf/cache-ispn.xml`.\n+\n+The cache configuration is a regular https://infinispan.org/docs/stable/titles/configuring/configuring.html[Infinispan] configuration file.\n+\n+=== Overview: Cache types and Defaults\n+\n+.Local caches\n+Keycloak caches persistent data locally to avoid unnecessary database requests. The caches used are:\n+\n+* realms\n+* users\n+* authorization\n+* keys\n+\n+.Invalidation of local caches\n+Local caching improves performance, but adds a challenge in multi-node setups: When one Keycloak node updates data in the shared database, all other nodes need to be aware of it, so they invalidate that data from their caches. The `work` cache is used for sending these invalidation messages.\n+\n+.Authentication sessions\n+Authentication sessions are started when an unauthenticated user or service tries to login to Keycloak. The `authenticationSessions` distributed cache is used to save data during authentication of particular user.\n+\n+.User sessions\n+There are four distributed caches for sessions of authenticated users and services:\n+\n+* sessions\n+* clientSessions\n+* offlineSessions\n+* offlineClientSessions\n+\n+These caches are used to save data about user sessions, and clients attached to the sessions.\n+\n+.Password brute force detection\n+The `loginFailures` distributed cache is used to track data about failed login attempts. This cache is needed for the Brute Force Protection feature to work correctly in a multi-node Keycloak setup.\n+\n+.Action tokens\n+Action tokens are used for scenarios when a user needs to confirm an action asynchronously, for example in the emails sent by the forgot password flow. The `actionTokens` distributed cache is used to track metadata about action tokens.\n+\n+The following table gives an overview of the specific caches Keycloak uses. These caches are configured in `conf/cache-ispn.xml`:\n+\n+|====\n+|Cache name|Cache Type|Description\n+|realms|Local|Cache persisted realm data\n+|users|Local|Cache persisted user data\n+|authorization|Local|Cache persisted authorization data\n+|keys|Local|Cache external public keys\n+|work|Replicated|Propagate invalidation messages across nodes\n+|sessions|Distributed|Caches user sessions, when user is authenticated\n+|authenticationSessions|Distributed|Caches authentication sessions, when user is authenticating\n+|offlineSessions|Distributed|Caches offline sessions\n+|clientSessions|Distributed|Caches sessions for each client a user is authenticated with\n+|offlineClientSessions|Distributed|Caches offline client sessions\n+|loginFailures|Distributed|keep track of failed logins, fraud detection\n+|actionTokens|Distributed|Caches action Tokens\n+|====\n+\n+Local caches for realms, users and authorization are configured to have 10000 entries per default. The local key cache can hold up to 1000 entries per default and defaults to expire every 1h, so keys are forced to be periodically downloaded from external clients or identity providers.\n+\n+All distributed caches are set to have 2 owners per default, meaning 2 nodes having a copy of the specific cache entries. Non-owner nodes query the owners of a specific cache to obtain data. When both owner nodes are offline, all data gets lost. This usually leads to users being logged out at the next request and having to login again.\n+\n+=== Specify your own cache configuration file\n+\n+To specify your own cache configuration file, use:\n+\n+<@kc.build parameters=\"--cache-config-file=my-cache-file.xml\"/>\n+\n+== Transport stacks\n+Transport stacks ensure that distributed cache nodes in a cluster communicate in a reliable fashion. Keycloak supports a wide range of transport stacks:\n+\n+<@opts.expectedValues option=\"cache-stack\"/>\n+\n+To apply a specific cache stack, use:\n+\n+<@kc.build parameters=\"--cache-stack=<stack>\"/>\n+\n+The default stack is set to `UDP` when distributed caches are enabled.\n+\n+=== Available transport stacks\n+The following table shows transport stacks that are available without any further configuration than using the `--cache-stack` build option:\n+|===\n+|Stack name|Transport protocol|Discovery\n+|tcp|TCP|MPING (uses UDP multicast).\n+|udp|UDP|UDP multicast\n+|kubernetes|TCP|DNS_PING\n+|===\n+\n+=== Additional transport stacks\n+The following table shows transport stacks that are supported by Keycloak, but need some extra steps to work. Note that all of these are _not_ Kubernetes / OpenShift stacks, so you don't need to enable the \"google\" stack if you want to run Keycloak on top of Googles Kubernetes engine. In that case, use the `kubernetes` stack.\n+Instead, when you have a distributed cache setup running on AWS EC2 instances, you'd need to set the stack to `ec2`, because ec2 does not support a default discovery mechanism such as `UDP`.\n+\n+|===\n+|Stack name|Transport protocol|Discovery\n+|ec2|TCP|NATIVE_S3_PING\n+|google|TCP|GOOGLE_PING2\n+|azure|TCP|AZURE_PING\n+|===\n+\n+For the cloud vendor specific stacks to work, you have to provide additional dependencies to Keycloak. You can find more information, including Links to repositories providing the additional dependencies, in the https://infinispan.org/docs/dev/titles/embedding/embedding.html#jgroups-cloud-discovery-protocols_cluster-transport[official Infinispan documentation].\n+\n+To provide the dependencies to Keycloak, put the respective JAR in the `providers` directory and `build` Keycloak afterwards, using\n+\n+<@kc.build parameters=\"--cache-stack=<ec2|google|azure>\"/>\n+\n+=== Securing cache communication\n+The current Infinispan cache implementation should be secured by various security measures such as RBAC, ACLs and Transport stack encryption. Please refer to the https://infinispan.org/docs/dev/titles/security/security.html#[Infinispan security guide] for more information about securing cache communication.\n+\n+</@tmpl.guide>\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/features.adoc", "new_path": "docs/guides/src/main/server/features.adoc", "diff": "<#import \"/templates/guide.adoc\" as tmpl>\n<#import \"/templates/kc.adoc\" as kc>\n-<#import \"/templates/options.adoc\" as opts>\n<@tmpl.guide\ntitle=\"Enabling and disabling features\"\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Configure Caching Guide V1 (#9903) * Configure Caching Guide V1 Closes #9459
339,500
26.01.2022 09:05:14
-3,600
0471ec494161bf32ce9cd6c67c2b1ebf64d4ba42
Cross-site validation for lazy loading of offline sessions & Switch default offline sessions to lazy loaded
[ { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProvider.java", "new_path": "model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProvider.java", "diff": "@@ -34,8 +34,10 @@ import org.keycloak.models.ModelException;\nimport org.keycloak.models.OfflineUserSessionModel;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\n+import org.keycloak.models.UserProvider;\nimport org.keycloak.models.UserSessionModel;\nimport org.keycloak.models.UserSessionProvider;\n+import org.keycloak.models.UserSessionSpi;\nimport org.keycloak.models.session.UserSessionPersisterProvider;\nimport org.keycloak.models.sessions.infinispan.changes.Tasks;\nimport org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStore;\n@@ -108,7 +110,7 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\nprotected final RemoteCacheInvoker remoteCacheInvoker;\nprotected final InfinispanKeyGenerator keyGenerator;\n- protected final boolean loadOfflineSessionsStatsFromDatabase;\n+ protected final boolean loadOfflineSessionsFromDatabase;\npublic InfinispanUserSessionProvider(KeycloakSession session,\nRemoteCacheInvoker remoteCacheInvoker,\n@@ -120,7 +122,7 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\nCache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionCache,\nCache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache,\nCache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionCache,\n- boolean loadOfflineSessionsStatsFromDatabase) {\n+ boolean loadOfflineSessionsFromDatabase) {\nthis.session = session;\nthis.sessionCache = sessionCache;\n@@ -140,7 +142,7 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\nthis.persisterLastSessionRefreshStore = persisterLastSessionRefreshStore;\nthis.remoteCacheInvoker = remoteCacheInvoker;\nthis.keyGenerator = keyGenerator;\n- this.loadOfflineSessionsStatsFromDatabase = loadOfflineSessionsStatsFromDatabase;\n+ this.loadOfflineSessionsFromDatabase = loadOfflineSessionsFromDatabase;\nsession.getTransactionManager().enlistAfterCompletion(clusterEventsSenderTx);\nsession.getTransactionManager().enlistAfterCompletion(sessionTx);\n@@ -341,28 +343,39 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\nprotected Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, UserSessionPredicate predicate, boolean offline) {\n- if (offline && loadOfflineSessionsStatsFromDatabase) {\n+ if (offline && loadOfflineSessionsFromDatabase) {\n// fetch the offline user-sessions from the persistence provider\nUserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);\n+ if (predicate.getUserId() != null) {\nUserModel user = session.users().getUserById(realm, predicate.getUserId());\nif (user != null) {\n- return persister.loadUserSessionsStream(realm, user, offline, 0, null);\n+ return persister.loadUserSessionsStream(realm, user, true, 0, null);\n}\n-\n- if (predicate.getBrokerSessionId() != null) {\n- // TODO add support for offline user-session lookup by brokerSessionId\n- // currently it is not possible to access the brokerSessionId in offline user-session in a database agnostic way\n- throw new ModelException(\"Dynamic database lookup for offline user-sessions by brokerSessionId is currently only supported for preloaded sessions.\");\n}\nif (predicate.getBrokerUserId() != null) {\n- // TODO add support for offline user-session lookup by brokerUserId\n- // currently it is not possible to access the brokerUserId in offline user-session in a database agnostic way\n- throw new ModelException(\"Dynamic database lookup for offline user-sessions by brokerUserId is currently only supported for preloaded sessions.\");\n+ String[] idpAliasSessionId = predicate.getBrokerUserId().split(\"\\\\.\");\n+\n+ Map<String, String> attributes = new HashMap<>();\n+ attributes.put(UserModel.IDP_ALIAS, idpAliasSessionId[0]);\n+ attributes.put(UserModel.IDP_USER_ID, idpAliasSessionId[1]);\n+\n+ UserProvider userProvider = session.getProvider(UserProvider.class);\n+ UserModel userModel = userProvider.searchForUserStream(realm, attributes, 0, null).findFirst().orElse(null);\n+ return userModel != null ?\n+ persister.loadUserSessionsStream(realm, userModel, true, 0, null) :\n+ Stream.empty();\n}\n+ if (predicate.getBrokerSessionId() != null) {\n+ // TODO add support for offline user-session lookup by brokerSessionId\n+ // currently it is not possible to access the brokerSessionId in offline user-session in a database agnostic way\n+ throw new ModelException(\"Dynamic database lookup for offline user-sessions by broker session ID is currently only supported for preloaded sessions. \" +\n+ \"Set preloadOfflineSessionsFromDatabase option to \\\"true\\\" in \" + UserSessionSpi.NAME + \" SPI in \"\n+ + InfinispanUserSessionProviderFactory.PROVIDER_ID + \" provider to enable the lookup.\");\n+ }\n}\nCache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);\n@@ -421,10 +434,10 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\nprotected Stream<UserSessionModel> getUserSessionsStream(final RealmModel realm, ClientModel client, Integer firstResult, Integer maxResults, final boolean offline) {\n- if (offline && loadOfflineSessionsStatsFromDatabase) {\n+ if (offline && loadOfflineSessionsFromDatabase) {\n// fetch the actual offline user session count from the database\nUserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);\n- return persister.loadUserSessionsStream(realm, client, offline, firstResult, maxResults);\n+ return persister.loadUserSessionsStream(realm, client, true, firstResult, maxResults);\n}\nfinal String clientUuid = client.getId();\n@@ -516,9 +529,9 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\n@Override\npublic Map<String, Long> getActiveClientSessionStats(RealmModel realm, boolean offline) {\n- if (offline && loadOfflineSessionsStatsFromDatabase) {\n+ if (offline && loadOfflineSessionsFromDatabase) {\nUserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);\n- return persister.getUserSessionsCountsByClients(realm, offline);\n+ return persister.getUserSessionsCountsByClients(realm, true);\n}\nCache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);\n@@ -536,10 +549,10 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\nprotected long getUserSessionsCount(RealmModel realm, ClientModel client, boolean offline) {\n- if (offline && loadOfflineSessionsStatsFromDatabase) {\n+ if (offline && loadOfflineSessionsFromDatabase) {\n// fetch the actual offline user session count from the database\nUserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);\n- return persister.getUserSessionsCount(realm, client, offline);\n+ return persister.getUserSessionsCount(realm, client, true);\n}\nCache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);\n@@ -782,7 +795,7 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\n@Override\npublic Stream<UserSessionModel> getOfflineUserSessionsStream(RealmModel realm, UserModel user) {\n- if (loadOfflineSessionsStatsFromDatabase) {\n+ if (loadOfflineSessionsFromDatabase) {\nreturn getUserSessionsFromPersistenceProviderStream(realm, user, true);\n}\n" }, { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProviderFactory.java", "new_path": "model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProviderFactory.java", "diff": "@@ -79,6 +79,8 @@ public class InfinispanUserSessionProviderFactory implements UserSessionProvider\npublic static final String REMOVE_USER_SESSIONS_EVENT = \"REMOVE_USER_SESSIONS_EVENT\";\n+ private boolean preloadOfflineSessionsFromDatabase;\n+\nprivate Config.Scope config;\nprivate RemoteCacheInvoker remoteCacheInvoker;\n@@ -95,15 +97,14 @@ public class InfinispanUserSessionProviderFactory implements UserSessionProvider\nCache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache = connections.getCache(InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME);\nCache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionsCache = connections.getCache(InfinispanConnectionProvider.OFFLINE_CLIENT_SESSION_CACHE_NAME);\n- boolean loadOfflineSessionsStatsFromDatabase = !isPreloadingOfflineSessionsFromDatabaseEnabled();\n-\nreturn new InfinispanUserSessionProvider(session, remoteCacheInvoker, lastSessionRefreshStore, offlineLastSessionRefreshStore,\n- persisterLastSessionRefreshStore, keyGenerator, cache, offlineSessionsCache, clientSessionCache, offlineClientSessionsCache, loadOfflineSessionsStatsFromDatabase);\n+ persisterLastSessionRefreshStore, keyGenerator, cache, offlineSessionsCache, clientSessionCache, offlineClientSessionsCache, !preloadOfflineSessionsFromDatabase);\n}\n@Override\npublic void init(Config.Scope config) {\nthis.config = config;\n+ preloadOfflineSessionsFromDatabase = config.getBoolean(\"preloadOfflineSessionsFromDatabase\", false);\n}\n@Override\n@@ -147,10 +148,6 @@ public class InfinispanUserSessionProviderFactory implements UserSessionProvider\n});\n}\n- private boolean isPreloadingOfflineSessionsFromDatabaseEnabled() {\n- return config.getBoolean(\"preloadOfflineSessionsFromDatabase\", true);\n- }\n-\n// Max count of worker errors. Initialization will end with exception when this number is reached\nprivate int getMaxErrors() {\nreturn config.getInt(\"maxErrors\", 20);\n@@ -175,7 +172,7 @@ public class InfinispanUserSessionProviderFactory implements UserSessionProvider\n@Override\npublic void run(KeycloakSession session) {\n- if (isPreloadingOfflineSessionsFromDatabaseEnabled()) {\n+ if (preloadOfflineSessionsFromDatabase) {\n// only preload offline-sessions if necessary\nlog.debug(\"Start pre-loading userSessions from persistent storage\");\n@@ -340,7 +337,6 @@ public class InfinispanUserSessionProviderFactory implements UserSessionProvider\nlog.debugf(\"Pre-loading sessions from remote cache '%s' finished\", cacheName);\n}\n-\n@Override\npublic void close() {\n}\n" }, { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/JpaUserSessionPersisterProvider.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/JpaUserSessionPersisterProvider.java", "diff": "@@ -259,24 +259,21 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv\nString offlineStr = offlineToString(offline);\n- Query query = em.createNamedQuery(\"findUserSessionsCountsByClientId\");\n+ TypedQuery<Object[]> query = em.createNamedQuery(\"findClientSessionsClientIds\", Object[].class);\nquery.setParameter(\"offline\", offlineStr);\nquery.setParameter(\"realmId\", realm.getId());\n- Map<String, Long> offlineSessionsByClient = new HashMap<>();\n-\n- closing(query.getResultStream()).forEach(record -> {\n-\n- Object[] row = (Object[]) record;\n-\n- String clientId = String.valueOf(row[0]);\n- Long count = ((Number)row[1]).longValue();\n-\n- offlineSessionsByClient.put(clientId, count);\n- });\n-\n- return offlineSessionsByClient;\n+ return closing(query.getResultStream())\n+ .collect(Collectors.toMap(row -> {\n+ String clientId = row[0].toString();\n+ if (clientId.equals(PersistentClientSessionEntity.EXTERNAL)) {\n+ final String externalClientId = row[1].toString();\n+ final String clientStorageProvider = row[2].toString();\n+ clientId = new StorageId(clientStorageProvider, externalClientId).getId();\n+ }\n+ return clientId;\n+ }, row -> (Long) row[3]));\n}\n@Override\n@@ -319,14 +316,23 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv\npublic Stream<UserSessionModel> loadUserSessionsStream(RealmModel realm, ClientModel client, boolean offline, Integer firstResult, Integer maxResults) {\nString offlineStr = offlineToString(offline);\n-\n- TypedQuery<PersistentUserSessionEntity> query = paginateQuery(\n+ TypedQuery<PersistentUserSessionEntity> query;\n+ StorageId clientStorageId = new StorageId(client.getId());\n+ if (clientStorageId.isLocal()) {\n+ query = paginateQuery(\nem.createNamedQuery(\"findUserSessionsByClientId\", PersistentUserSessionEntity.class),\nfirstResult, maxResults);\n+ query.setParameter(\"clientId\", client.getId());\n+ } else {\n+ query = paginateQuery(\n+ em.createNamedQuery(\"findUserSessionsByExternalClientId\", PersistentUserSessionEntity.class),\n+ firstResult, maxResults);\n+ query.setParameter(\"clientStorageProvider\", clientStorageId.getProviderId());\n+ query.setParameter(\"externalClientId\", clientStorageId.getExternalId());\n+ }\nquery.setParameter(\"offline\", offlineStr);\nquery.setParameter(\"realmId\", realm.getId());\n- query.setParameter(\"clientId\", client.getId());\nreturn loadUserSessionsWithClientSessions(query, offlineStr);\n}\n@@ -461,11 +467,20 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv\npublic int getUserSessionsCount(RealmModel realm, ClientModel clientModel, boolean offline) {\nString offlineStr = offlineToString(offline);\n+ Query query;\n+ StorageId clientStorageId = new StorageId(clientModel.getId());\n+ if (clientStorageId.isLocal()) {\n+ query = em.createNamedQuery(\"findClientSessionsCountByClient\");\n+ query.setParameter(\"clientId\", clientModel.getId());\n+ } else {\n+ query = em.createNamedQuery(\"findClientSessionsCountByExternalClient\");\n+ query.setParameter(\"clientStorageProvider\", clientStorageId.getProviderId());\n+ query.setParameter(\"externalClientId\", clientStorageId.getExternalId());\n+ }\n- Query query = em.createNamedQuery(\"findClientSessionsCountByClient\");\n- // Note, that realm is unused here, since the clientModel id already determines the offline user-sessions bound to a owning realm.\n+ // Note, that realm is unused here, since the clientModel id already determines the offline user-sessions bound to an owning realm.\nquery.setParameter(\"offline\", offlineStr);\n- query.setParameter(\"clientId\", clientModel.getId());\n+\nNumber n = (Number) query.getSingleResult();\nreturn n.intValue();\n}\n" }, { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java", "diff": "@@ -41,7 +41,8 @@ import java.io.Serializable;\n//@NamedQuery(name=\"deleteExpiredClientSessions\", query=\"delete from PersistentClientSessionEntity sess where sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.realmId = :realmId AND u.offline = :offline AND u.lastSessionRefresh < :lastSessionRefresh)\"),\n@NamedQuery(name=\"findClientSessionsByUserSession\", query=\"select sess from PersistentClientSessionEntity sess where sess.userSessionId=:userSessionId and sess.offline = :offline\"),\n@NamedQuery(name=\"findClientSessionsOrderedById\", query=\"select sess from PersistentClientSessionEntity sess where sess.offline = :offline and sess.userSessionId >= :fromSessionId and sess.userSessionId <= :toSessionId order by sess.userSessionId\"),\n- @NamedQuery(name=\"findClientSessionsCountByClient\", query=\"select count(sess) from PersistentClientSessionEntity sess where sess.offline = :offline and sess.clientId = :clientId\")\n+ @NamedQuery(name=\"findClientSessionsCountByClient\", query=\"select count(sess) from PersistentClientSessionEntity sess where sess.offline = :offline and sess.clientId = :clientId\"),\n+ @NamedQuery(name=\"findClientSessionsCountByExternalClient\", query=\"select count(sess) from PersistentClientSessionEntity sess where sess.offline = :offline and sess.clientStorageProvider = :clientStorageProvider and sess.externalClientId = :externalClientId\")\n})\n@Table(name=\"OFFLINE_CLIENT_SESSION\")\n@Entity\n" }, { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentUserSessionEntity.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentUserSessionEntity.java", "diff": "@@ -47,14 +47,14 @@ import java.io.Serializable;\n\" AND sess.realmId = :realmId AND sess.userId = :userId ORDER BY sess.userSessionId\"),\n@NamedQuery(name=\"findUserSessionsByClientId\", query=\"SELECT sess FROM PersistentUserSessionEntity sess INNER JOIN PersistentClientSessionEntity clientSess \" +\n\" ON sess.userSessionId = clientSess.userSessionId AND clientSess.clientId = :clientId WHERE sess.offline = :offline \" +\n- \" AND sess.userSessionId = clientSess.userSessionId AND sess.realmId = :realmId ORDER BY sess.userSessionId\"),\n- @NamedQuery(name=\"findUserSessionsCountsByClientId\", query=\"SELECT clientSess.clientId, count(clientSess) \" +\n- \" FROM PersistentUserSessionEntity sess INNER JOIN PersistentClientSessionEntity clientSess \" +\n- \" ON sess.userSessionId = clientSess.userSessionId \" +\n- // find all available offline user-session for all clients in a realm\n- \" WHERE sess.offline = :offline \" +\n- \" AND sess.userSessionId = clientSess.userSessionId AND sess.realmId = :realmId \" +\n- \" GROUP BY clientSess.clientId\")\n+ \" AND sess.realmId = :realmId ORDER BY sess.userSessionId\"),\n+ @NamedQuery(name=\"findUserSessionsByExternalClientId\", query=\"SELECT sess FROM PersistentUserSessionEntity sess INNER JOIN PersistentClientSessionEntity clientSess \" +\n+ \" ON sess.userSessionId = clientSess.userSessionId AND clientSess.clientStorageProvider = :clientStorageProvider AND clientSess.externalClientId = :externalClientId WHERE sess.offline = :offline \" +\n+ \" AND sess.realmId = :realmId ORDER BY sess.userSessionId\"),\n+ @NamedQuery(name=\"findClientSessionsClientIds\", query=\"SELECT clientSess.clientId, clientSess.externalClientId, clientSess.clientStorageProvider, count(clientSess)\" +\n+ \" FROM PersistentClientSessionEntity clientSess INNER JOIN PersistentUserSessionEntity sess ON clientSess.userSessionId = sess.userSessionId \" +\n+ \" WHERE sess.offline = :offline AND sess.realmId = :realmId \" +\n+ \" GROUP BY clientSess.clientId, clientSess.externalClientId, clientSess.clientStorageProvider\")\n})\n@Table(name=\"OFFLINE_USER_SESSION\")\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/LogoutEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/LogoutEndpoint.java", "diff": "@@ -20,6 +20,7 @@ package org.keycloak.protocol.oidc.endpoints;\nimport org.jboss.logging.Logger;\nimport org.jboss.resteasy.annotations.cache.NoCache;\nimport org.jboss.resteasy.spi.HttpRequest;\n+import org.keycloak.Config;\nimport org.keycloak.OAuth2Constants;\nimport org.keycloak.OAuthErrorException;\nimport org.keycloak.TokenVerifier;\n@@ -96,12 +97,16 @@ public class LogoutEndpoint {\nprivate RealmModel realm;\nprivate EventBuilder event;\n+ // When enabled we cannot search offline sessions by brokerSessionId. We need to search by federated userId and then filter by brokerSessionId.\n+ private boolean offlineSessionsLazyLoadingEnabled;\n+\nprivate Cors cors;\npublic LogoutEndpoint(TokenManager tokenManager, RealmModel realm, EventBuilder event) {\nthis.tokenManager = tokenManager;\nthis.realm = realm;\nthis.event = event;\n+ this.offlineSessionsLazyLoadingEnabled = !Config.scope(\"userSessions\").scope(\"infinispan\").getBoolean(\"preloadOfflineSessionsFromDatabase\", false);\n}\n@Path(\"/\")\n@@ -318,7 +323,7 @@ public class LogoutEndpoint {\nif (logoutToken.getSid() != null) {\nbackchannelLogoutResponse = backchannelLogoutWithSessionId(logoutToken.getSid(), identityProviderAliases,\n- logoutOfflineSessions);\n+ logoutOfflineSessions, logoutToken.getSubject());\n} else {\nbackchannelLogoutResponse = backchannelLogoutFederatedUserId(logoutToken.getSubject(),\nidentityProviderAliases, logoutOfflineSessions);\n@@ -349,7 +354,7 @@ public class LogoutEndpoint {\n}\nprivate BackchannelLogoutResponse backchannelLogoutWithSessionId(String sessionId,\n- Stream<String> identityProviderAliases, boolean logoutOfflineSessions) {\n+ Stream<String> identityProviderAliases, boolean logoutOfflineSessions, String federatedUserId) {\nAtomicReference<BackchannelLogoutResponse> backchannelLogoutResponse = new AtomicReference<>(new BackchannelLogoutResponse());\nbackchannelLogoutResponse.get().setLocalLogoutSucceeded(true);\nidentityProviderAliases.forEach(identityProviderAlias -> {\n@@ -357,8 +362,12 @@ public class LogoutEndpoint {\nidentityProviderAlias + \".\" + sessionId);\nif (logoutOfflineSessions) {\n+ if (offlineSessionsLazyLoadingEnabled) {\n+ logoutOfflineUserSessionByBrokerUserId(identityProviderAlias + \".\" + federatedUserId, identityProviderAlias + \".\" + sessionId);\n+ } else {\nlogoutOfflineUserSession(identityProviderAlias + \".\" + sessionId);\n}\n+ }\nif (userSession != null) {\nbackchannelLogoutResponse.set(logoutUserSession(userSession));\n@@ -407,6 +416,15 @@ public class LogoutEndpoint {\n.forEach(userSessionManager::revokeOfflineUserSession);\n}\n+ private void logoutOfflineUserSessionByBrokerUserId(String brokerUserId, String brokerSessionId) {\n+ UserSessionManager userSessionManager = new UserSessionManager(session);\n+ if (brokerUserId != null && brokerSessionId != null) {\n+ session.sessions().getOfflineUserSessionByBrokerUserIdStream(realm, brokerUserId)\n+ .filter(userSession -> brokerSessionId.equals(userSession.getBrokerSessionId()))\n+ .forEach(userSessionManager::revokeOfflineUserSession);\n+ }\n+ }\n+\nprivate BackchannelLogoutResponse logoutUserSession(UserSessionModel userSession) {\nBackchannelLogoutResponse backchannelLogoutResponse = AuthenticationManager.backchannelLogout(session, realm,\nuserSession, session.getContext().getUri(), clientConnection, headers, false);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/servers/auth-server/jboss/common/ant/configure.xml", "new_path": "testsuite/integration-arquillian/servers/auth-server/jboss/common/ant/configure.xml", "diff": "</resources>\n<filterset>\n<filter token=\"HOTROD_SASL_MECHANISM\" value=\"${hotrod.sasl.mechanism}\"/>\n+ <filter token=\"PRELOADING_ENABLED\" value=\"${keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase}\"/>\n</filterset>\n</copy>\n<copy todir=\"${auth.server.home}/standalone/configuration\">\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/servers/auth-server/jboss/common/jboss-cli/cross-dc-setup.cli", "new_path": "testsuite/integration-arquillian/servers/auth-server/jboss/common/jboss-cli/cross-dc-setup.cli", "diff": "@@ -145,3 +145,7 @@ echo *** Update undertow subsystem ***\necho *** Update keycloak-server subsystem, infinispan remoteStoreSecurity ***\n/subsystem=keycloak-server/spi=connectionsInfinispan/provider=default:map-put(name=properties,key=remoteStoreSecurityEnabled,value=${keycloak.connectionsInfinispan.default.remoteStoreSecurityEnabled:true})\n+\n+echo *** Enable offline user session preloading ***\n+/subsystem=keycloak-server/spi=userSessions:add(default-provider=infinispan)\n+/subsystem=keycloak-server/spi=userSessions/provider=infinispan:add(properties={preloadOfflineSessionsFromDatabase => @PRELOADING_ENABLED@},enabled=true)\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/servers/auth-server/jboss/pom.xml", "new_path": "testsuite/integration-arquillian/servers/auth-server/jboss/pom.xml", "diff": "<ant.scenario>scenario-crossdc</ant.scenario>\n<h2.jdbc.url>jdbc:h2:tcp://localhost:9092/mem:keycloak-dc-shared;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</h2.jdbc.url>\n+\n+ <keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>true</keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>\n</properties>\n<build>\n<plugins>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/crossdc/SessionsPreloadCrossDCTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/crossdc/SessionsPreloadCrossDCTest.java", "diff": "@@ -25,7 +25,6 @@ import org.junit.Test;\nimport org.keycloak.OAuth2Constants;\nimport org.keycloak.common.util.Retry;\nimport org.keycloak.connections.infinispan.InfinispanConnectionProvider;\n-import org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.admin.ApiUtil;\nimport org.keycloak.testsuite.arquillian.CrossDCTestEnricher;\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java", "diff": "@@ -194,23 +194,48 @@ public class ClientStorageTest extends AbstractTestRealmKeycloakTest {\npublic void testClientStats() throws Exception {\ntestDirectGrant(\"hardcoded-client\");\ntestDirectGrant(\"hardcoded-client\");\n+ testDirectGrant(\"direct-grant\");\ntestBrowser(\"test-app\");\n- offlineTokenDirectGrantFlowNoRefresh();\n+ offlineTokenDirectGrantFlowNoRefresh(\"hardcoded-client\");\n+ offlineTokenDirectGrantFlowNoRefresh(\"hardcoded-client\");\n+ offlineTokenDirectGrantFlowNoRefresh(\"direct-grant\");\n+ offlineTokenDirectGrantFlowNoRefresh(\"direct-grant\");\nList<Map<String, String>> list = adminClient.realm(\"test\").getClientSessionStats();\nboolean hardTested = false;\nboolean testAppTested = false;\n+ boolean directTested = false;\nfor (Map<String, String> entry : list) {\nif (entry.get(\"clientId\").equals(\"hardcoded-client\")) {\n- Assert.assertEquals(\"3\", entry.get(\"active\"));\n- Assert.assertEquals(\"1\", entry.get(\"offline\"));\n+ Assert.assertEquals(\"4\", entry.get(\"active\"));\n+ Assert.assertEquals(\"2\", entry.get(\"offline\"));\nhardTested = true;\n} else if (entry.get(\"clientId\").equals(\"test-app\")) {\nAssert.assertEquals(\"1\", entry.get(\"active\"));\nAssert.assertEquals(\"0\", entry.get(\"offline\"));\ntestAppTested = true;\n+ } else if (entry.get(\"clientId\").equals(\"direct-grant\")) {\n+ Assert.assertEquals(\"3\", entry.get(\"active\"));\n+ Assert.assertEquals(\"2\", entry.get(\"offline\"));\n+ directTested = true;\n}\n}\n- Assert.assertTrue(hardTested && testAppTested);\n+ Assert.assertTrue(hardTested && testAppTested && directTested);\n+\n+ testingClient.server().run(session -> {\n+ RealmModel realm = session.realms().getRealmByName(\"test\");\n+\n+ ClientModel hardcoded = realm.getClientByClientId(\"hardcoded-client\");\n+ long activeUserSessions = session.sessions().getActiveUserSessions(realm, hardcoded);\n+ long offlineSessionsCount = session.sessions().getOfflineSessionsCount(realm, hardcoded);\n+ Assert.assertEquals(4, activeUserSessions);\n+ Assert.assertEquals(2, offlineSessionsCount);\n+\n+ ClientModel direct = realm.getClientByClientId(\"direct-grant\");\n+ activeUserSessions = session.sessions().getActiveUserSessions(realm, direct);\n+ offlineSessionsCount = session.sessions().getOfflineSessionsCount(realm, direct);\n+ Assert.assertEquals(3, activeUserSessions);\n+ Assert.assertEquals(2, offlineSessionsCount);\n+ });\n}\n@@ -460,9 +485,9 @@ public class ClientStorageTest extends AbstractTestRealmKeycloakTest {\n// Assert same token can be refreshed again\ntestRefreshWithOfflineToken(token, offlineToken, offlineTokenString, token.getSessionState(), userId);\n}\n- public void offlineTokenDirectGrantFlowNoRefresh() throws Exception {\n+ public void offlineTokenDirectGrantFlowNoRefresh(String clientId) throws Exception {\noauth.scope(OAuth2Constants.OFFLINE_ACCESS);\n- oauth.clientId(\"hardcoded-client\");\n+ oauth.clientId(clientId);\nOAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest(\"password\", \"test-user@localhost\", \"password\");\nAssert.assertNull(tokenResponse.getErrorDescription());\nAccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/resources/arquillian.xml", "new_path": "testsuite/integration-arquillian/tests/base/src/test/resources/arquillian.xml", "diff": "\"keycloak.connectionsInfinispan.remoteStorePort\": \"${keycloak.connectionsInfinispan.remoteStorePort:11222}\",\n\"keycloak.connectionsInfinispan.remoteStoreEnabled\": \"${keycloak.connectionsInfinispan.remoteStoreEnabled:true}\",\n\"keycloak.connectionsInfinispan.hotrodProtocolVersion\": \"${keycloak.connectionsInfinispan.hotrodProtocolVersion}\",\n+ \"keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase\": \"${keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase:true}\",\n\"keycloak.connectionsJpa.url\": \"${keycloak.connectionsJpa.url.crossdc:jdbc:h2:mem:test-dc-shared}\",\n\"keycloak.connectionsJpa.driver\": \"${keycloak.connectionsJpa.driver.crossdc:org.h2.Driver}\",\n\"keycloak.connectionsJpa.driverDialect\": \"${keycloak.connectionsJpa.driverDialect.crossdc:}\"\n\"keycloak.connectionsInfinispan.remoteStorePort\": \"${keycloak.connectionsInfinispan.remoteStorePort:11222}\",\n\"keycloak.connectionsInfinispan.remoteStoreEnabled\": \"${keycloak.connectionsInfinispan.remoteStoreEnabled:true}\",\n\"keycloak.connectionsInfinispan.hotrodProtocolVersion\": \"${keycloak.connectionsInfinispan.hotrodProtocolVersion}\",\n+ \"keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase\": \"${keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase:true}\",\n\"keycloak.connectionsJpa.url\": \"${keycloak.connectionsJpa.url.crossdc:jdbc:h2:mem:test-dc-shared}\",\n\"keycloak.connectionsJpa.driver\": \"${keycloak.connectionsJpa.driver.crossdc:org.h2.Driver}\",\n\"keycloak.connectionsJpa.driverDialect\": \"${keycloak.connectionsJpa.driverDialect.crossdc:}\"\n\"keycloak.connectionsInfinispan.remoteStorePort\": \"${keycloak.connectionsInfinispan.remoteStorePort.2:11222}\",\n\"keycloak.connectionsInfinispan.remoteStoreEnabled\": \"${keycloak.connectionsInfinispan.remoteStoreEnabled:true}\",\n\"keycloak.connectionsInfinispan.hotrodProtocolVersion\": \"${keycloak.connectionsInfinispan.hotrodProtocolVersion}\",\n+ \"keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase\": \"${keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase:true}\",\n\"keycloak.connectionsJpa.url\": \"${keycloak.connectionsJpa.url.crossdc:jdbc:h2:mem:test-dc-shared}\",\n\"keycloak.connectionsJpa.driver\": \"${keycloak.connectionsJpa.driver.crossdc:org.h2.Driver}\",\n\"keycloak.connectionsJpa.driverDialect\": \"${keycloak.connectionsJpa.driverDialect.crossdc:}\"\n\"keycloak.connectionsInfinispan.remoteStorePort\": \"${keycloak.connectionsInfinispan.remoteStorePort.2:11222}\",\n\"keycloak.connectionsInfinispan.remoteStoreEnabled\": \"${keycloak.connectionsInfinispan.remoteStoreEnabled:true}\",\n\"keycloak.connectionsInfinispan.hotrodProtocolVersion\": \"${keycloak.connectionsInfinispan.hotrodProtocolVersion}\",\n+ \"keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase\": \"${keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase:true}\",\n\"keycloak.connectionsJpa.url\": \"${keycloak.connectionsJpa.url.crossdc:jdbc:h2:mem:test-dc-shared}\",\n\"keycloak.connectionsJpa.driver\": \"${keycloak.connectionsJpa.driver.crossdc:org.h2.Driver}\",\n\"keycloak.connectionsJpa.driverDialect\": \"${keycloak.connectionsJpa.driverDialect.crossdc:}\"\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/pom.xml", "new_path": "testsuite/model/pom.xml", "diff": "<log4j.configuration>file:${project.build.directory}/dependency/log4j.properties</log4j.configuration>\n<jacoco.skip>true</jacoco.skip>\n<keycloak.profile.feature.map_storage>disabled</keycloak.profile.feature.map_storage>\n- <keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>true</keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>\n+ <keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>false</keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>\n</properties>\n<dependencies>\n</profile>\n<profile>\n- <id>jpa+infinispan-sessions-preloading-disabled</id>\n+ <id>jpa+cross-dc-infinispan-offline-sessions-preloading</id>\n+ <properties>\n+ <keycloak.model.parameters>CrossDCInfinispan,Jpa</keycloak.model.parameters>\n+ <keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>true</keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>\n+ </properties>\n+ </profile>\n+\n+ <profile>\n+ <id>jpa+infinispan-offline-sessions-preloading</id>\n<properties>\n<keycloak.model.parameters>Infinispan,Jpa</keycloak.model.parameters>\n- <keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>false</keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>\n+ <keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>true</keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>\n</properties>\n</profile>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionProviderOfflineModelTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionProviderOfflineModelTest.java", "diff": "package org.keycloak.testsuite.model.session;\n+import org.infinispan.Cache;\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.keycloak.common.util.Time;\n+import org.keycloak.connections.infinispan.InfinispanConnectionProvider;\nimport org.keycloak.models.AuthenticatedClientSessionModel;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.Constants;\n@@ -40,10 +42,17 @@ import org.keycloak.timer.TimerProvider;\nimport java.util.HashMap;\nimport java.util.HashSet;\n+import java.util.LinkedList;\n+import java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n+import java.util.concurrent.CountDownLatch;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+import java.util.concurrent.atomic.AtomicInteger;\n+import java.util.concurrent.atomic.AtomicReference;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n+\nimport org.keycloak.testsuite.model.KeycloakModelTest;\nimport org.keycloak.testsuite.model.RequireProvider;\n@@ -297,6 +306,73 @@ public class UserSessionProviderOfflineModelTest extends KeycloakModelTest {\n}\n}\n+ @Test\n+ public void testOfflineSessionLazyLoading() throws InterruptedException {\n+ AtomicReference<List<UserSessionModel>> offlineUserSessions = new AtomicReference<>(new LinkedList<>());\n+ AtomicReference<List<AuthenticatedClientSessionModel>> offlineClientSessions = new AtomicReference<>(new LinkedList<>());\n+ createOfflineSessions(\"user1\", 10, offlineUserSessions, offlineClientSessions);\n+\n+ closeKeycloakSessionFactory();\n+\n+ AtomicBoolean result = new AtomicBoolean(true);\n+ CountDownLatch latch = new CountDownLatch(4);\n+ inIndependentFactories(4, 300, () -> {\n+ withRealm(realmId, (session, realm) -> {\n+ final UserModel user = session.users().getUserByUsername(realm, \"user1\");\n+ result.set(result.get() && assertOfflineSession(offlineUserSessions, session.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList())));\n+ return null;\n+ });\n+\n+ latch.countDown();\n+\n+ awaitLatch(latch);\n+ });\n+\n+ Assert.assertTrue(result.get());\n+ }\n+\n+ @Test\n+ public void testOfflineSessionLazyLoadingPropagationBetweenNodes() throws InterruptedException {\n+ AtomicReference<List<UserSessionModel>> offlineUserSessions = new AtomicReference<>(new LinkedList<>());\n+ AtomicReference<List<AuthenticatedClientSessionModel>> offlineClientSessions = new AtomicReference<>(new LinkedList<>());\n+ AtomicBoolean result = new AtomicBoolean(true);\n+ AtomicInteger index = new AtomicInteger();\n+ CountDownLatch latch = new CountDownLatch(4);\n+ CountDownLatch afterFirstNodeLatch = new CountDownLatch(1);\n+\n+ inIndependentFactories(4, 300, () -> {\n+ if (index.incrementAndGet() == 1) {\n+ createOfflineSessions(\"user1\", 10, offlineUserSessions, offlineClientSessions);\n+\n+ afterFirstNodeLatch.countDown();\n+ }\n+ awaitLatch(afterFirstNodeLatch);\n+\n+ log.debug(\"Joining the cluster\");\n+ inComittedTransaction(session -> {\n+ InfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\n+ Cache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);\n+ do {\n+ try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n+ } while (! cache.getAdvancedCache().getDistributionManager().isJoinComplete());\n+ cache.keySet().forEach(s -> {});\n+ });\n+ log.debug(\"Cluster joined\");\n+\n+ withRealm(realmId, (session, realm) -> {\n+ final UserModel user = session.users().getUserByUsername(realm, \"user1\");\n+ result.set(result.get() && assertOfflineSession(offlineUserSessions, session.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList())));\n+ return null;\n+ });\n+\n+ latch.countDown();\n+\n+ awaitLatch(latch);\n+ });\n+\n+ Assert.assertTrue(result.get());\n+ }\n+\nprivate static Set<String> createOfflineSessionIncludeClientSessions(KeycloakSession session, UserSessionModel\nuserSession) {\nSet<String> offlineSessions = new HashSet<>();\n@@ -308,4 +384,40 @@ public class UserSessionProviderOfflineModelTest extends KeycloakModelTest {\nreturn offlineSessions;\n}\n+\n+ private void createOfflineSessions(String username, int sessionsPerUser, AtomicReference<List<UserSessionModel>> offlineUserSessions, AtomicReference<List<AuthenticatedClientSessionModel>> offlineClientSessions) {\n+ withRealm(realmId, (session, realm) -> {\n+ final UserModel user = session.users().getUserByUsername(realm, username);\n+ ClientModel testAppClient = realm.getClientByClientId(\"test-app\");\n+ ClientModel thirdPartyClient = realm.getClientByClientId(\"third-party\");\n+\n+ IntStream.range(0, sessionsPerUser)\n+ .mapToObj(index -> session.sessions().createUserSession(realm, user, username + index, \"ip\" + index, \"auth\", false, null, null))\n+ .forEach(userSession -> {\n+ AuthenticatedClientSessionModel testAppClientSession = session.sessions().createClientSession(realm, testAppClient, userSession);\n+ AuthenticatedClientSessionModel thirdPartyClientSession = session.sessions().createClientSession(realm, thirdPartyClient, userSession);\n+ UserSessionModel offlineUserSession = session.sessions().createOfflineUserSession(userSession);\n+ offlineUserSessions.get().add(offlineUserSession);\n+ offlineClientSessions.get().add(session.sessions().createOfflineClientSession(testAppClientSession, offlineUserSession));\n+ offlineClientSessions.get().add(session.sessions().createOfflineClientSession(thirdPartyClientSession, offlineUserSession));\n+ });\n+\n+ return null;\n+ });\n+ }\n+\n+ private boolean assertOfflineSession(AtomicReference<List<UserSessionModel>> expectedUserSessions, List<UserSessionModel> actualUserSessions) {\n+ boolean result = expectedUserSessions.get().size() == actualUserSessions.size();\n+ for (UserSessionModel userSession: expectedUserSessions.get()) {\n+ result = result && actualUserSessions.contains(userSession);\n+ }\n+ return result;\n+ }\n+\n+ private void awaitLatch(CountDownLatch latch) {\n+ try {\n+ latch.await();\n+ } catch (InterruptedException e) {\n+ }\n+ }\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Cross-site validation for lazy loading of offline sessions & Switch default offline sessions to lazy loaded
339,618
03.02.2022 11:25:54
-3,600
0f3293cf0012c50a14fa70647db27588a9420f1c
Do not show full help when providing an invalid option Closes
[ { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java", "diff": "@@ -282,7 +282,7 @@ public final class Picocli {\nCommandLine cmd = new CommandLine(spec);\ncmd.setExecutionExceptionHandler(new ExecutionExceptionHandler());\n-\n+ cmd.setParameterExceptionHandler(new ShortErrorMessageHandler());\ncmd.setHelpFactory(new HelpFactory());\ncmd.getHelpSectionMap().put(SECTION_KEY_COMMAND_LIST, new SubCommandListRenderer());\ncmd.setErr(new PrintWriter(System.err, true));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/ShortErrorMessageHandler.java", "diff": "+package org.keycloak.quarkus.runtime.cli;\n+\n+import picocli.CommandLine;\n+import picocli.CommandLine.IParameterExceptionHandler;\n+import picocli.CommandLine.ParameterException;\n+import picocli.CommandLine.UnmatchedArgumentException;\n+import picocli.CommandLine.Help;\n+import picocli.CommandLine.Model.CommandSpec;\n+\n+import java.io.PrintWriter;\n+\n+public class ShortErrorMessageHandler implements IParameterExceptionHandler {\n+\n+ public int handleParseException(ParameterException ex, String[] args) {\n+ CommandLine cmd = ex.getCommandLine();\n+ PrintWriter writer = cmd.getErr();\n+\n+ writer.println(cmd.getColorScheme().errorText(ex.getMessage()));\n+ UnmatchedArgumentException.printSuggestions(ex, writer);\n+\n+ CommandSpec spec = cmd.getCommandSpec();\n+ writer.printf(\"Try '%s --help' for more information on the available options.%n\", spec.qualifiedName());\n+\n+ return cmd.getExitCodeExceptionMapper() != null\n+ ? cmd.getExitCodeExceptionMapper().getExitCode(ex)\n+ : spec.exitCodeOnInvalidInput();\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/OptionValidationTest.java", "new_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/OptionValidationTest.java", "diff": "package org.keycloak.it.cli;\n-import org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\n-import org.keycloak.it.junit5.extension.CLIResult;\nimport org.keycloak.it.junit5.extension.CLITest;\nimport io.quarkus.test.junit.main.Launch;\nimport io.quarkus.test.junit.main.LaunchResult;\n-import io.quarkus.test.junit.main.QuarkusMainLauncher;\n+\n+import static org.junit.jupiter.api.Assertions.assertEquals;\n+import static org.junit.jupiter.api.Assertions.assertTrue;\n@CLITest\npublic class OptionValidationTest {\n@@ -32,12 +32,19 @@ public class OptionValidationTest {\n@Test\n@Launch({\"build\", \"--db\"})\npublic void failMissingOptionValue(LaunchResult result) {\n- Assertions.assertTrue(result.getErrorOutput().contains(\"Missing required value for option '--db' (vendor). Expected values are: h2-file, h2-mem, mariadb, mssql, mysql, oracle, postgres\"));\n+ assertTrue(result.getErrorOutput().contains(\"Missing required value for option '--db' (vendor). Expected values are: h2-file, h2-mem, mariadb, mssql, mysql, oracle, postgres\"));\n}\n@Test\n@Launch({\"build\", \"--db\", \"foo\", \"bar\"})\npublic void failMultipleOptionValue(LaunchResult result) {\n- Assertions.assertTrue(result.getErrorOutput().contains(\"Option '--db' expects a single value (vendor) Expected values are: h2-file, h2-mem, mariadb, mssql, mysql, oracle, postgres\"));\n+ assertTrue(result.getErrorOutput().contains(\"Option '--db' expects a single value (vendor) Expected values are: h2-file, h2-mem, mariadb, mssql, mysql, oracle, postgres\"));\n+ }\n+\n+ @Test\n+ @Launch({\"build\", \"--nosuch\"})\n+ public void failUnknownOption(LaunchResult result) {\n+ assertEquals(\"Unknown option: '--nosuch'\\n\" +\n+ \"Try 'kc.sh build --help' for more information on the available options.\", result.getErrorOutput());\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Do not show full help when providing an invalid option Closes #9956
339,181
03.02.2022 15:42:04
18,000
d8c5f9e2fcdd61b3c64f03a22fbaa4bc8ce58db0
Edits to the reverse proxy Suggested deny and allow instead of black/white listed Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/reverseproxy.adoc", "new_path": "docs/guides/src/main/server/reverseproxy.adoc", "diff": "<@tmpl.guide\ntitle=\"Configuring a reverse proxy\"\n-summary=\"Learn how to configure Keycloak together with a reverse proxy, api gateway or load balancer.\"\n+summary=\"Learn how to configure Keycloak together with a reverse proxy, api gateway, or load balancer.\"\nincludedOptions=\"proxy proxy-*\">\n-It is pretty common nowadays to use a reverse proxy in distributed environments. If you want to use Keycloak together with such a proxy, you can use different proxy modes depending on the TLS termination in your specific environment:\n+Distributed environments frequently require the use of a reverse proxy.\n+For Keycloak, your choice of proxy modes depends on the TLS termination in your environment.\n-== Available proxy modes\n-The `none` mode disables proxy support. It is the default mode.\n+== Proxy modes\n+The following proxy modes are available:\n-The `edge` mode enables communication through HTTP between the proxy and Keycloak. This mode is suitable for deployments with a highly secure internal network where the reverse proxy keeps a secure connection (HTTP over TLS) with clients while communicating with Keycloak using HTTP.\n+none:: Disables proxy support.\n+It is the default mode.\n-The `reencrypt` mode requires communication through HTTPS between the proxy and Keycloak. This mode is suitable for deployments where internal communication between the reverse proxy and Keycloak should also be protected, and different keys and certificates are used on the reverse proxy as well as on Keycloak.\n+edge:: Enables communication through HTTP between the proxy and Keycloak.\n+This mode is suitable for deployments with a highly secure internal network where the reverse proxy keeps a secure connection (HTTP over TLS) with clients while communicating with Keycloak using HTTP.\n-The `passthrough` mode enables communication through HTTP or HTTPS between the proxy and Keycloak. This mode is suitable for deployments where the reverse proxy is not terminating TLS, but only forwarding the requests to the Keycloak server so that secure connections between the server and clients are based on the keys and certificates used by the Keycloak server itself.\n+reencrypt:: Requires communication through HTTPS between the proxy and Keycloak.\n+This mode is suitable for deployments where internal communication between the reverse proxy and Keycloak should also be protected.\n+Different keys and certificates are used on the reverse proxy as well as on Keycloak.\n+\n+passthrough:: Enables communication through HTTP or HTTPS between the proxy and Keycloak.\n+This mode is suitable for deployments where the reverse proxy is not terminating TLS.\n+The proxy instead is forwarding requests to the Keycloak server so that secure connections between the server and clients are based on the keys and certificates used by the Keycloak server.\n== Configure the proxy mode in Keycloak\n-To select the proxy mode, run:\n+To select the proxy mode, enter this command:\n<@kc.start parameters=\"--proxy <mode>\"/>\n== Configure the reverse proxy\n-Make sure your reverse proxy is configured correctly. To do so, please:\n-\n-* Properly set X-Forwarded-For and X-Forwarded-Proto HTTP headers.\n+Make sure your reverse proxy is configured correctly by performing these actions:\n+* Set the X-Forwarded-For and X-Forwarded-Proto HTTP headers.\n* Preserve the original 'Host' HTTP header.\n-Please consult the documentation of your reverse proxy on how to set these headers.\n+To set these headers, consult the documentation for your reverse proxy.\n-Take extra precautions to ensure that the X-Forwarded-For header is set by your reverse proxy. If it is not configured correctly, rogue clients can set this header themselves and trick Keycloak into thinking the client is connecting from a different IP address than it actually does. This may become really important if you are doing any black or white listing of IP addresses.\n+Take extra precautions to ensure that the X-Forwarded-For header is set by your reverse proxy.\n+If this header is incorrectly configured, rogue clients can set this header and trick Keycloak into thinking the client is connected from a different IP address than the actual address.\n+This precaution can more be critical if you do any deny or allow listing of IP addresses.\n=== Exposed path recommendations\n-When using a reverse proxy, not all paths have to be exposed in order for Keycloak to work correctly. The recommendations on which paths to expose and which not to expose are as follows:\n+When using a reverse proxy, Keylcoak only requires certain paths need to be exposed.\n+The following table shows the recommended paths to expose.\n|===\n|Keycloak Path|Reverse Proxy Path|Exposed|Reason\n@@ -43,32 +54,32 @@ When using a reverse proxy, not all paths have to be exposed in order for Keyclo\n|/\n|-\n|No\n-|When exposing all paths, admin paths are exposed unnecessarily\n+|When exposing all paths, admin paths are exposed unnecessarily.\n|/admin/\n| -\n|No\n-|Exposed admin paths lead to an unnecessary attack vector\n+|Exposed admin paths lead to an unnecessary attack vector.\n|/js/\n| -\n|No\n-|It's good practice to not use external js for the javascript client, but bake it into your public client instead\n+|A good practice is to not use external js for the javascript client, but bake it into your public client instead.\n|/welcome/\n| -\n|No\n-|No need to expose the welcome page after initial installation.\n+|No need exists to expose the welcome page after initial installation.\n|/realms/\n|/realms/\n|Yes\n-|Needed to work correctly (e.g. oidc endpoints)\n+|This path is needed to work correctly, for example, for OIDC endpoints.\n|/resources/\n|/resources/\n|Yes\n-|Needed to serve assets correctly. May be served from a CDN instead of the Keycloak path.\n+|This path is needed to serve assets correctly. It may be served from a CDN instead of the Keycloak path.\n|/robots.txt\n|/robots.txt\n@@ -76,6 +87,7 @@ When using a reverse proxy, not all paths have to be exposed in order for Keyclo\n|Search engine rules\n|===\n-We assume you run Keycloak on the root path `/` on your reverse proxy/gateways public API. If not, prefix the path with your desired one.\n+We assume you run Keycloak on the root path `/` on your reverse proxy/gateway's public API.\n+If not, prefix the path with your desired one.\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Edits to the reverse proxy Suggested deny and allow instead of black/white listed Closes #9982
339,181
02.02.2022 17:36:50
18,000
eedf1ef6cb2f3fa2a07586ec0b61c67d2f406c44
9925 Review of the hostname topic
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/hostname.adoc", "new_path": "docs/guides/src/main/server/hostname.adoc", "diff": "@@ -7,44 +7,43 @@ title=\"Configure the Hostname\"\nsummary=\"Learn how to configure the frontend and backchannel endpoints exposed by Keycloak.\"\nincludedOptions=\"hostname-* proxy\">\n-When running Keycloak in environments such as Kubernetes, OpenShift or even on-premise, you usually do not want to expose the internal URLs to the public facing internet. Instead, you want to use your public hostname. This guide will show you how to configure Keycloak to use the right hostname for different scenarios.\n+When running Keycloak in environments such as Kubernetes, OpenShift, or on-premise, you want to protect the internal URLs from exposure to the public facing internet. You want to use your public hostname. This guide describes how to configure Keycloak to use the right hostname for different scenarios.\n== Keycloak API Endpoint categories\n-Keycloak exposes three different API endpoint categories, each using a specific base URL. These categories are:\n+As this section explains, Keycloak exposes three API endpoint categories: frontend, backend, and administrative. Each category uses a specific base URL.\n=== Frontend Endpoints\n-Frontend endpoints are used to externally access Keycloak. When no Hostname is set, the base URL used for the frontend is taken from the incoming request. This has some major disadvantages, e.g. in High availability setups spanning multiple Keycloak instances, where it should not depend on the instance the request lands what URL is used, but instead one URL should be used for all instances, so they are seen as one system from the outside.\n+Frontend endpoints are used to externally access Keycloak. When no hostname is set, the base URL used for the frontend is taken from the incoming request. This choice has some major disadvantages. For example, in a high availability scenario, you may have multiple Keycloak instances. The choice of URL should not depend on the instance where the request lands. The URL should be used for all instances, so they are seen as one system from the outside.\n-The `hostname` property can be used to set the hostname part of the frontend base URL:\n+To set the hostname part of the frontend base URL, enter the `kc.start` command in this format:\n<@kc.start parameters=\"--hostname=<value>\"/>\n=== Backend Endpoints\n-Backend endpoints are used for direct communication between Keycloak and applications. Examples are the Token endpoint or the User info endpoint. Backend endpoints are also taking the base URL from the request by default. To override this behaviour, set the `hostname-strict-backchannel` configuration option:\n+Backend endpoints are used for direct communication between Keycloak and applications. Examples of backend endpoints are the Token endpoint and the User info endpoint. Backend endpoints are also taking the base URL from the request by default. To override this behavior, set the `hostname-strict-backchannel` configuration option by entering the `kc.start` command in this format:\n<@kc.start parameters=\"--hostname=<value> --hostname-strict-backchannel=true\"/>\n-When all applications connected to Keycloak communicate through the public URL, set `hostname-strict-backchannel` to true. Otherwise, leave it as false to allow internal applications to communicate with Keycloak through an internal URL\n+When all applications connected to Keycloak communicate through the public URL, set `hostname-strict-backchannel` to true. Otherwise, leave this parameter as false to allow internal applications to communicate with Keycloak through an internal URL.\n=== Administrative Endpoints\n-When the admin console is exposed on a different hostname, use `--hostname-admin` to link to it:\n+When the Admin Console is exposed on a different hostname, use `--hostname-admin` to link to it. Enter the `kc.start` command in this format:\n<@kc.start parameters=\"--hostname=<hostname> --hostname-admin=<adminHostname>\"/>\n-When `hostname-admin` is configured, all links and static resources used to render the admin console are served from the value you enter for `<adminHostname>` instead of using `<hostname>`.\n+When `hostname-admin` is configured, all links and static resources used to render the Admin Console are served from the value you enter for `<adminHostname>` instead of the value for `<hostname>`.\n-Keycloaks administration endpoints and its admin console should not be publicly accessible at all to reduce attack surface, so you might want to secure them using a reverse proxy. For more information about which paths to expose using a reverse proxy, please refer to the <@links.server id=\"proxy\"/> Guide.\n+To reduce attack surface, the administration endpoints for Keycloak and the Admin Console should not be publicly accessible. Therefore, you can secure them by using a reverse proxy. For more information about which paths to expose using a reverse proxy, see the <@links.server id=\"proxy\"/> Guide.\n== Overriding the hostname path\n-When running behind a reverse proxy, you may expose Keycloak using a different context path such as `myproxy.url/mykeycloak`. To do this, you can override the hostname path to use the path defined in your reverse proxy:\n+When running Keycloak behind a reverse proxy, you may expose Keycloak using a different context path such as `myproxy.url/mykeycloak`. To perform this action, you can override the hostname path to use the path defined in your reverse proxy:\n<@kc.start parameters=\"--hostname=myurl --hostname-path=mykeycloak\"/>\n-\n-The `hostname-path` configuration only takes effect when a reverse proxy is enabled. Please see the <@links.server id=\"proxy\"/> Guide for details.\n+The `hostname-path` configuration takes effect when a reverse proxy is enabled. For details, see the <@links.server id=\"proxy\"/> Guide.\n== Using the hostname in development mode\n-When running Keycloak in development mode by using `start-dev`, the hostname setting is optional. When the `hostname` is not specified the incoming request headers will be used.\n+You run Keycloak in development mode by using `start-dev`. In this mode, the hostname setting is optional. When it is omitted, the incoming request headers are used.\n=== Example: Hostname in development mode\n.Keycloak configuration:\n@@ -63,16 +62,16 @@ curl GET \"https://localhost:8080/realms/master/.well-known/openid-configuration\"\n# Backend endpoints: request://request:request -> http://localhost:8080\n----\n-Invoking the curl GET request above when running in development mode will show you the current OpenID Discovery configuration. In this configuration, all base URLS will be taken from the incoming request, so `http://localhost:8080` will be used for all endpoints.\n+In this example of using a curl GET request, the result shows the current OpenID Discovery configuration. All base URLS are taken from the incoming request, so `http://localhost:8080` is used for all endpoints.\n== Example Scenarios\n-Here are a few more example scenarios and the corresponding commands for setting up a hostname.\n+The following are more example scenarios and the corresponding commands for setting up a hostname.\n=== Assumptions for all scenarios\n* Keycloak is set up using HTTPS certificates and Port 8443.\n-* `intlUrl` refers to an internal IP/DNS for Keycloak\n+* `intlUrl` refers to an internal IP/DNS for Keycloak.\n* `myUrl` refers to an exposed public URL\n-* Keycloak runs in production mode using the `start` command\n+* Keycloak runs in production mode using the `start` command.\n=== Example 1: Hostname configuration without reverse proxy\n.Keycloak configuration:\n" } ]
Java
Apache License 2.0
keycloak/keycloak
9925 Review of the hostname topic
339,181
03.02.2022 11:20:55
18,000
4e2e81df23dc050b8527f1a8a2599f9f9531644b
Addressing Stian's comments Changing references to kc.start Closes 9925
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/hostname.adoc", "new_path": "docs/guides/src/main/server/hostname.adoc", "diff": "@@ -7,43 +7,61 @@ title=\"Configure the Hostname\"\nsummary=\"Learn how to configure the frontend and backchannel endpoints exposed by Keycloak.\"\nincludedOptions=\"hostname-* proxy\">\n-When running Keycloak in environments such as Kubernetes, OpenShift, or on-premise, you want to protect the internal URLs from exposure to the public facing internet. You want to use your public hostname. This guide describes how to configure Keycloak to use the right hostname for different scenarios.\n+When running Keycloak in environments such as Kubernetes, OpenShift, or on-premise, you want to protect the internal URLs from exposure to the public facing internet.\n+You want to use your public hostname.\n+This guide describes how to configure Keycloak to use the right hostname for different scenarios.\n== Keycloak API Endpoint categories\n-As this section explains, Keycloak exposes three API endpoint categories: frontend, backend, and administrative. Each category uses a specific base URL.\n+As this section explains, Keycloak exposes three API endpoint categories: frontend, backend, and administrative.\n+Each category uses a specific base URL.\n=== Frontend Endpoints\n-Frontend endpoints are used to externally access Keycloak. When no hostname is set, the base URL used for the frontend is taken from the incoming request. This choice has some major disadvantages. For example, in a high availability scenario, you may have multiple Keycloak instances. The choice of URL should not depend on the instance where the request lands. The URL should be used for all instances, so they are seen as one system from the outside.\n+Frontend endpoints are used to externally access Keycloak.\n+When no hostname is set, the base URL used for the frontend is taken from the incoming request.\n+This choice has some major disadvantages.\n+For example, in a high availability scenario, you may have multiple Keycloak instances.\n+The choice of URL should not depend on the instance where the request lands.\n+The URL should be used for all instances, so they are seen as one system from the outside.\n-To set the hostname part of the frontend base URL, enter the `kc.start` command in this format:\n+To set the hostname part of the frontend base URL, enter this command:\n<@kc.start parameters=\"--hostname=<value>\"/>\n=== Backend Endpoints\n-Backend endpoints are used for direct communication between Keycloak and applications. Examples of backend endpoints are the Token endpoint and the User info endpoint. Backend endpoints are also taking the base URL from the request by default. To override this behavior, set the `hostname-strict-backchannel` configuration option by entering the `kc.start` command in this format:\n+Backend endpoints are used for direct communication between Keycloak and applications.\n+Examples of backend endpoints are the Token endpoint and the User info endpoint.\n+Backend endpoints are also taking the base URL from the request by default.\n+To override this behavior, set the `hostname-strict-backchannel` configuration option by entering this command:\n<@kc.start parameters=\"--hostname=<value> --hostname-strict-backchannel=true\"/>\n-When all applications connected to Keycloak communicate through the public URL, set `hostname-strict-backchannel` to true. Otherwise, leave this parameter as false to allow internal applications to communicate with Keycloak through an internal URL.\n+When all applications connected to Keycloak communicate through the public URL, set `hostname-strict-backchannel` to true.\n+Otherwise, leave this parameter as false to allow internal applications to communicate with Keycloak through an internal URL.\n=== Administrative Endpoints\n-When the Admin Console is exposed on a different hostname, use `--hostname-admin` to link to it. Enter the `kc.start` command in this format:\n+When the Admin Console is exposed on a different hostname, use `--hostname-admin` to link to it as shown in this example:\n<@kc.start parameters=\"--hostname=<hostname> --hostname-admin=<adminHostname>\"/>\nWhen `hostname-admin` is configured, all links and static resources used to render the Admin Console are served from the value you enter for `<adminHostname>` instead of the value for `<hostname>`.\n-To reduce attack surface, the administration endpoints for Keycloak and the Admin Console should not be publicly accessible. Therefore, you can secure them by using a reverse proxy. For more information about which paths to expose using a reverse proxy, see the <@links.server id=\"proxy\"/> Guide.\n+To reduce attack surface, the administration endpoints for Keycloak and the Admin Console should not be publicly accessible.\n+Therefore, you can secure them by using a reverse proxy.\n+For more information about which paths to expose using a reverse proxy, see the <@links.server id=\"proxy\"/> Guide.\n== Overriding the hostname path\n-When running Keycloak behind a reverse proxy, you may expose Keycloak using a different context path such as `myproxy.url/mykeycloak`. To perform this action, you can override the hostname path to use the path defined in your reverse proxy:\n+When running Keycloak behind a reverse proxy, you may expose Keycloak using a different context path such as `myproxy.url/mykeycloak`.\n+To perform this action, you can override the hostname path to use the path defined in your reverse proxyas shown in this example:\n<@kc.start parameters=\"--hostname=myurl --hostname-path=mykeycloak\"/>\n-The `hostname-path` configuration takes effect when a reverse proxy is enabled. For details, see the <@links.server id=\"proxy\"/> Guide.\n+The `hostname-path` configuration takes effect when a reverse proxy is enabled.\n+For details, see the <@links.server id=\"proxy\"/> Guide.\n== Using the hostname in development mode\n-You run Keycloak in development mode by using `start-dev`. In this mode, the hostname setting is optional. When it is omitted, the incoming request headers are used.\n+You run Keycloak in development mode by using `start-dev`.\n+In this mode, the hostname setting is optional.\n+When it is omitted, the incoming request headers are used.\n=== Example: Hostname in development mode\n.Keycloak configuration:\n@@ -62,7 +80,8 @@ curl GET \"https://localhost:8080/realms/master/.well-known/openid-configuration\"\n# Backend endpoints: request://request:request -> http://localhost:8080\n----\n-In this example of using a curl GET request, the result shows the current OpenID Discovery configuration. All base URLS are taken from the incoming request, so `http://localhost:8080` is used for all endpoints.\n+In this example of using a curl GET request, the result shows the current OpenID Discovery configuration.\n+All base URLS are taken from the incoming request, so `http://localhost:8080` is used for all endpoints.\n== Example Scenarios\nThe following are more example scenarios and the corresponding commands for setting up a hostname.\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Addressing Stian's comments Changing references to kc.start Closes 9925
339,618
03.02.2022 12:38:46
-3,600
a592fae626f141857a7e569f7ad384f863506d50
Fix success on invalid build Closes
[ { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java", "diff": "package org.keycloak.quarkus.runtime.cli;\n-import static java.util.Arrays.asList;\nimport static org.keycloak.quarkus.runtime.cli.command.AbstractStartCommand.AUTO_BUILD_OPTION_LONG;\nimport static org.keycloak.quarkus.runtime.cli.command.AbstractStartCommand.AUTO_BUILD_OPTION_SHORT;\nimport static org.keycloak.quarkus.runtime.configuration.ConfigArgsConfigSource.hasOptionValue;\n@@ -77,15 +76,24 @@ public final class Picocli {\nCommandLine cmd = createCommandLine(cliArgs);\nif (Environment.isRebuildCheck()) {\n- runReAugmentationIfNeeded(cliArgs, cmd);\n- Quarkus.asyncExit(cmd.getCommandSpec().exitCodeOnSuccess());\n+ int exitCode = runReAugmentationIfNeeded(cliArgs, cmd);\n+ exitOnFailure(exitCode, cmd);\nreturn;\n}\n- cmd.execute(cliArgs.toArray(new String[0]));\n+ int exitCode = cmd.execute(cliArgs.toArray(new String[0]));\n+ exitOnFailure(exitCode, cmd);\n}\n- private static void runReAugmentationIfNeeded(List<String> cliArgs, CommandLine cmd) {\n+ private static void exitOnFailure(int exitCode, CommandLine cmd) {\n+ if (exitCode != cmd.getCommandSpec().exitCodeOnSuccess() && !Environment.isTestLaunchMode()) {\n+ // hard exit wanted, as build failed and no subsequent command should be executed. no quarkus involved.\n+ System.exit(exitCode);\n+ }\n+ }\n+\n+ private static int runReAugmentationIfNeeded(List<String> cliArgs, CommandLine cmd) {\n+ int exitCode = 0;\nif (hasAutoBuildOption(cliArgs) && !isHelpCommand(cliArgs)) {\nif (cliArgs.contains(StartDev.NAME)) {\nString profile = Environment.getProfile();\n@@ -96,9 +104,10 @@ public final class Picocli {\n}\n}\nif (requiresReAugmentation(cmd)) {\n- runReAugmentation(cliArgs, cmd);\n+ exitCode = runReAugmentation(cliArgs, cmd);\n}\n}\n+ return exitCode;\n}\nprivate static boolean isHelpCommand(List<String> cliArgs) {\n@@ -154,7 +163,9 @@ public final class Picocli {\nreturn properties;\n}\n- private static void runReAugmentation(List<String> cliArgs, CommandLine cmd) {\n+ private static int runReAugmentation(List<String> cliArgs, CommandLine cmd) {\n+ int exitCode = 0;\n+\nList<String> configArgsList = new ArrayList<>(cliArgs);\nconfigArgsList.remove(AUTO_BUILD_OPTION_LONG);\n@@ -170,11 +181,13 @@ public final class Picocli {\n}\n});\n- cmd.execute(configArgsList.toArray(new String[0]));\n+ exitCode = cmd.execute(configArgsList.toArray(new String[0]));\n- if(!isDevMode()) {\n+ if(!isDevMode() && exitCode == cmd.getCommandSpec().exitCodeOnSuccess()) {\ncmd.getOut().printf(\"Next time you run the server, just run:%n%n\\t%s %s %s%n%n\", Environment.getCommand(), Start.NAME, String.join(\" \", getSanitizedRuntimeCliOptions()));\n}\n+\n+ return exitCode;\n}\nprivate static boolean hasProviderChanges() {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Fix success on invalid build Closes #9790
339,618
04.02.2022 15:19:10
-3,600
e7abfef3e71b0492af4fbd6af9359e531fddb058
Production readiness guide V1 * Production readiness guide V1 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/guides/src/main/server/production-readiness.adoc", "diff": "+<#import \"/templates/guide.adoc\" as tmpl>\n+<#import \"/templates/kc.adoc\" as kc>\n+<#import \"/templates/links.adoc\" as links>\n+\n+<@tmpl.guide\n+title=\"Configuring Keycloak for production\"\n+summary=\"Learn how to make Keycloak ready for production.\"\n+includedOptions=\"\">\n+\n+Keycloak is used in various production environments, from on-premise deployments spanning only a few thousand users to deployments serving millions of users with secure authentication and authorization.\n+\n+This guide walks you through the general aspects of setting up a production ready Keycloak environment. It focusses on the main concepts and aspects instead of the actual implementation, which depends on your actual environment, be it containerized, on-premise, GitOps or Ansible. The key aspects covered in this guide apply to all of these environments.\n+\n+== Enabling TLS\n+Keycloak exchanges sensitive data all the time, so all communication from and to Keycloak needs to be done through a secure communication channel. For that, you must enable HTTP over TLS, or HTTPS, to prevent several attack vectors.\n+\n+The <@links.server id=\"enabletls\"/> and <@links.server id=\"outgoinghttp\"/> guides will show you the appropriate configuration to set up secure communication channels for Keycloak.\n+\n+== Setting the hostname for Keycloak\n+Keycloak instances in production usually run in a private network, but Keycloak needs to expose different public facing endpoints to communicate with applications that will be secured.\n+\n+Learn in the <@links.server id=\"hostname\"/> guide what the different endpoint categories are and how to configure the public hostname for them, depending on your specific environment.\n+\n+== Configure a reverse proxy\n+Apart from <<Setting the hostname for Keycloak>>, production environments usually use a reverse proxy / load balancer component to separate and unify access to the companies network. Using such a component is recommended for Keycloak production deployments.\n+\n+In the <@links.server id=\"reverseproxy\"/> guide you can find the available proxy communication modes in Keycloak and how to configure them. There's also a recommendation which paths should not be exposed to the public at all, and which paths need to be exposed for Keycloak to be able to secure your applications.\n+\n+== Configure a production grade database\n+The database used by Keycloak is crucial for the overall performance, availability, reliability and integrity of Keycloak. In the <@links.server id=\"db\"/> guide you can find the supported database vendors and how to configure Keycloak to use them.\n+\n+== Run Keycloak in a cluster\n+You'd not want every login to fail when your Keycloak instance goes down, so typical production deployments consist of two or more Keycloak instances.\n+\n+Keycloak uses JGroups and Infinispan under the covers to provide a reliable, HA-ready stack to run in a clustered scenario. When deployed to a cluster the embedded Infinispan server communication should be secured. Either by enabling authentication and encryption, or through isolating the network used for cluster communication.\n+\n+To find out more about using multiple nodes, the different caches and the right stack for your environment, see the <@links.server id=\"caching\"/> guide.\n+\n+</@tmpl.guide>\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/reverseproxy.adoc", "new_path": "docs/guides/src/main/server/reverseproxy.adoc", "diff": "@@ -33,7 +33,9 @@ To select the proxy mode, enter this command:\n<@kc.start parameters=\"--proxy <mode>\"/>\n== Configure the reverse proxy\n-Make sure your reverse proxy is configured correctly by performing these actions:\n+Some Keycloak features rely on the assumption that the remote address of the HTTP request connecting to Keycloak is the real IP address of the clients machine.\n+\n+When you have a reverse proxy or loadbalancer in front of Keycloak, this might not be the case, so please make sure your reverse proxy is configured correctly by performing these actions:\n* Set the X-Forwarded-For and X-Forwarded-Proto HTTP headers.\n* Preserve the original 'Host' HTTP header.\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Production readiness guide V1 (#10000) * Production readiness guide V1 Closes #9463
339,511
04.01.2022 12:25:42
-32,400
07d43f31f3dd836b9e4ebe9b4ea33df9da08f972
Expected Scopes of ClientScopesCondition created on Admin UI are not saved onto ClientScopesCondition.Configuration Closes
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientScopesCondition.java", "new_path": "services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientScopesCondition.java", "diff": "@@ -59,7 +59,7 @@ public class ClientScopesCondition extends AbstractClientPolicyConditionProvider\npublic static class Configuration extends ClientPolicyConditionConfigurationRepresentation {\nprotected String type;\n- protected List<String> scope;\n+ protected List<String> scopes;\npublic String getType() {\nreturn type;\n@@ -69,12 +69,12 @@ public class ClientScopesCondition extends AbstractClientPolicyConditionProvider\nthis.type = type;\n}\n- public List<String> getScope() {\n- return scope;\n+ public List<String> getScopes() {\n+ return scopes;\n}\n- public void setScope(List<String> scope) {\n- this.scope = scope;\n+ public void setScopes(List<String> scope) {\n+ this.scopes = scope;\n}\n}\n@@ -155,7 +155,7 @@ public class ClientScopesCondition extends AbstractClientPolicyConditionProvider\n}\nprivate Set<String> getScopesForMatching() {\n- List<String> scopes = configuration.getScope();\n+ List<String> scopes = configuration.getScopes();\nif (scopes == null) return null;\nreturn new HashSet<>(scopes);\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractClientPoliciesTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractClientPoliciesTest.java", "diff": "@@ -1140,7 +1140,7 @@ public abstract class AbstractClientPoliciesTest extends AbstractKeycloakTest {\nprotected void assertExpectedClientScopesCondition(String type, List<String> scopes, ClientPolicyRepresentation policyRep) {\nClientScopesCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientScopesConditionFactory.PROVIDER_ID, ClientScopesCondition.Configuration.class);\nAssert.assertEquals(cfg.getType(), type);\n- Assert.assertEquals(cfg.getScope(), scopes);\n+ Assert.assertEquals(cfg.getScopes(), scopes);\n}\nprotected void assertExpectedClientUpdateContextCondition(List<String> updateClientSources, ClientPolicyRepresentation policyRep) {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java", "diff": "@@ -331,7 +331,7 @@ public final class ClientPoliciesUtil {\npublic static ClientScopesCondition.Configuration createClientScopesConditionConfig(String type, List<String> scopes) {\nClientScopesCondition.Configuration config = new ClientScopesCondition.Configuration();\nconfig.setType(type);\n- config.setScope(scopes);\n+ config.setScopes(scopes);\nreturn config;\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Expected Scopes of ClientScopesCondition created on Admin UI are not saved onto ClientScopesCondition.Configuration Closes #9371
339,181
07.02.2022 03:22:11
18,000
aed6e8cd5b3e005ecddfbee852d39d9ad4c67394
Edits to caching topic Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/caching.adoc", "new_path": "docs/guides/src/main/server/caching.adoc", "diff": "@@ -7,26 +7,31 @@ title=\"Configuring distributed caches\"\nsummary=\"Understand how to configure the caching layer\"\nincludedOptions=\"cache cache-*\">\n-Keycloak is designed for high availability and multi-node clustered setups. The current distributed cache implementation is built on top of https://infinispan.org[Infinispan], a high-performance, distributable in-memory data grid.\n+Keycloak is designed for high availability and multi-node clustered setups.\n+The current distributed cache implementation is built on top of https://infinispan.org[Infinispan], a high-performance, distributable in-memory data grid.\nAll available cache options are build options, so they need to be applied to a `build` of Keycloak before starting.\n== Enable distributed caching\n-Caching is enabled per default when you start Keycloak in production mode, using the `start` command. This will automatically discover other Keycloak nodes in your network. To explicitly enable distributed infinispan caching, use:\n+When you start Keycloak in production mode, by using the `start` command, caching is enabled and all Keycloak nodes in your network are discovered.\n+\n+To explicitly enable distributed infinispan caching, enter this command:\n<@kc.build parameters=\"--cache=ispn\"/>\n-When you start Keycloak in development mode, using the `start-dev` command, Keycloak defaults to only use local caches using `--cache=local` instead. Using the `local` cache mode is intended only for development and testing purposes.\n+When you start Keycloak in development mode, by using the `start-dev` command, Keycloak uses only local caches, applying the `--cache=local` option.\n+The `local` cache mode is intended only for development and testing purposes.\n-== Configure Caches\n+== Configuring caches\nKeycloak provides a cache configuration file with sensible defaults located at `conf/cache-ispn.xml`.\n-The cache configuration is a regular https://infinispan.org/docs/stable/titles/configuring/configuring.html[Infinispan] configuration file.\n+The cache configuration is a regular https://infinispan.org/docs/stable/titles/configuring/configuring.html[Infinispan configuration file].\n-=== Overview: Cache types and Defaults\n+=== Cache types and defaults\n.Local caches\n-Keycloak caches persistent data locally to avoid unnecessary database requests. The caches used are:\n+Keycloak caches persistent data locally to avoid unnecessary database requests.\n+The following caches are used:\n* realms\n* users\n@@ -34,28 +39,34 @@ Keycloak caches persistent data locally to avoid unnecessary database requests.\n* keys\n.Invalidation of local caches\n-Local caching improves performance, but adds a challenge in multi-node setups: When one Keycloak node updates data in the shared database, all other nodes need to be aware of it, so they invalidate that data from their caches. The `work` cache is used for sending these invalidation messages.\n+Local caching improves performance, but adds a challenge in multi-node setups.\n+When one Keycloak node updates data in the shared database, all other nodes need to be aware of it, so they invalidate that data from their caches.\n+The `work` cache is used for sending these invalidation messages.\n.Authentication sessions\n-Authentication sessions are started when an unauthenticated user or service tries to login to Keycloak. The `authenticationSessions` distributed cache is used to save data during authentication of particular user.\n+Authentication sessions are started when an unauthenticated user or service tries to log in to Keycloak.\n+The `authenticationSessions` distributed cache is used to save data during authentication of a particular user.\n.User sessions\n-There are four distributed caches for sessions of authenticated users and services:\n+The following are the distributed caches for sessions of authenticated users and services:\n* sessions\n* clientSessions\n* offlineSessions\n* offlineClientSessions\n-These caches are used to save data about user sessions, and clients attached to the sessions.\n+These caches are used to save data about user sessions and clients attached to the sessions.\n.Password brute force detection\n-The `loginFailures` distributed cache is used to track data about failed login attempts. This cache is needed for the Brute Force Protection feature to work correctly in a multi-node Keycloak setup.\n+The `loginFailures` distributed cache is used to track data about failed login attempts.\n+This cache is needed for the Brute Force Protection feature to work in a multi-node Keycloak setup.\n.Action tokens\n-Action tokens are used for scenarios when a user needs to confirm an action asynchronously, for example in the emails sent by the forgot password flow. The `actionTokens` distributed cache is used to track metadata about action tokens.\n+Action tokens are used for scenarios when a user needs to confirm an action asynchronously, for example in the emails sent by the forgot password flow.\n+The `actionTokens` distributed cache is used to track metadata about action tokens.\n-The following table gives an overview of the specific caches Keycloak uses. These caches are configured in `conf/cache-ispn.xml`:\n+The following table gives an overview of the specific caches Keycloak uses.\n+You configure these caches in `conf/cache-ispn.xml`:\n|====\n|Cache name|Cache Type|Description\n@@ -73,22 +84,28 @@ The following table gives an overview of the specific caches Keycloak uses. Thes\n|actionTokens|Distributed|Caches action Tokens\n|====\n-Local caches for realms, users and authorization are configured to have 10000 entries per default. The local key cache can hold up to 1000 entries per default and defaults to expire every 1h, so keys are forced to be periodically downloaded from external clients or identity providers.\n+Local caches for realms, users, and authorization are configured to have 10,000 entries per default.\n+The local key cache can hold up to 1,000 entries per default and defaults to expire every one hour.\n+Therefore, keys are forced to be periodically downloaded from external clients or identity providers.\n-All distributed caches are set to have 2 owners per default, meaning 2 nodes having a copy of the specific cache entries. Non-owner nodes query the owners of a specific cache to obtain data. When both owner nodes are offline, all data gets lost. This usually leads to users being logged out at the next request and having to login again.\n+Each distributed cache has two owners per default, which means that two nodes have a copy of the specific cache entries.\n+Non-owner nodes query the owners of a specific cache to obtain data.\n+When both owner nodes are offline, all data is lost.\n+This situation usually leads to users being logged out at the next request and having to log in again.\n=== Specify your own cache configuration file\n-To specify your own cache configuration file, use:\n+To specify your own cache configuration file, enter this command:\n<@kc.build parameters=\"--cache-config-file=my-cache-file.xml\"/>\n== Transport stacks\n-Transport stacks ensure that distributed cache nodes in a cluster communicate in a reliable fashion. Keycloak supports a wide range of transport stacks:\n+Transport stacks ensure that distributed cache nodes in a cluster communicate in a reliable fashion.\n+Keycloak supports a wide range of transport stacks:\n<@opts.expectedValues option=\"cache-stack\"/>\n-To apply a specific cache stack, use:\n+To apply a specific cache stack, enter this command:\n<@kc.build parameters=\"--cache-stack=<stack>\"/>\n@@ -104,8 +121,10 @@ The following table shows transport stacks that are available without any furthe\n|===\n=== Additional transport stacks\n-The following table shows transport stacks that are supported by Keycloak, but need some extra steps to work. Note that all of these are _not_ Kubernetes / OpenShift stacks, so you don't need to enable the \"google\" stack if you want to run Keycloak on top of Googles Kubernetes engine. In that case, use the `kubernetes` stack.\n-Instead, when you have a distributed cache setup running on AWS EC2 instances, you'd need to set the stack to `ec2`, because ec2 does not support a default discovery mechanism such as `UDP`.\n+The following table shows transport stacks that are supported by Keycloak, but need some extra steps to work.\n+Note that _none_ of these stacks are Kubernetes / OpenShift stacks, so no need exists to enable the \"google\" stack if you want to run Keycloak on top of the Google Kubernetes engine.\n+In that case, use the `kubernetes` stack.\n+Instead, when you have a distributed cache setup running on AWS EC2 instances, you would need to set the stack to `ec2`, because ec2 does not support a default discovery mechanism such as `UDP`.\n|===\n|Stack name|Transport protocol|Discovery\n@@ -114,13 +133,14 @@ Instead, when you have a distributed cache setup running on AWS EC2 instances, y\n|azure|TCP|AZURE_PING\n|===\n-For the cloud vendor specific stacks to work, you have to provide additional dependencies to Keycloak. You can find more information, including Links to repositories providing the additional dependencies, in the https://infinispan.org/docs/dev/titles/embedding/embedding.html#jgroups-cloud-discovery-protocols_cluster-transport[official Infinispan documentation].\n+Cloud vendor specific stacks have additional dependencies for Keycloak.\n+For more information and links to repositories with these dependencies, see the https://infinispan.org/docs/dev/titles/embedding/embedding.html#jgroups-cloud-discovery-protocols_cluster-transport[Infinispan documentation].\n-To provide the dependencies to Keycloak, put the respective JAR in the `providers` directory and `build` Keycloak afterwards, using\n+To provide the dependencies to Keycloak, put the respective JAR in the `providers` directory and `build` Keycloak by entering this command:\n<@kc.build parameters=\"--cache-stack=<ec2|google|azure>\"/>\n=== Securing cache communication\n-The current Infinispan cache implementation should be secured by various security measures such as RBAC, ACLs and Transport stack encryption. Please refer to the https://infinispan.org/docs/dev/titles/security/security.html#[Infinispan security guide] for more information about securing cache communication.\n+The current Infinispan cache implementation should be secured by various security measures such as RBAC, ACLs, and Transport stack encryption. For more information about securing cache communication, see the https://infinispan.org/docs/dev/titles/security/security.html#[Infinispan security guide].\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Edits to caching topic (#9988) Closes #9968
339,410
25.01.2022 15:36:30
-3,600
de2c1fbb456cd18954f5cbb4836a36d0d1caa8e8
Update the entityVersion also for downgrades, as it needs to match the JSON and auxiliary tables. Will trigger also when changes to a child occur, like for example when attributes change. Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaMapStorageProviderFactory.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaMapStorageProviderFactory.java", "diff": "@@ -62,6 +62,8 @@ import org.keycloak.models.map.storage.MapStorageProviderFactory;\nimport org.keycloak.models.map.storage.jpa.client.JpaClientMapKeycloakTransaction;\nimport org.keycloak.models.map.storage.jpa.clientscope.JpaClientScopeMapKeycloakTransaction;\nimport org.keycloak.models.map.storage.jpa.clientscope.entity.JpaClientScopeEntity;\n+import org.keycloak.models.map.storage.jpa.hibernate.listeners.JpaEntityVersionListener;\n+import org.keycloak.models.map.storage.jpa.hibernate.listeners.JpaOptimisticLockingListener;\nimport org.keycloak.models.map.storage.jpa.role.JpaRoleMapKeycloakTransaction;\nimport org.keycloak.models.map.storage.jpa.role.entity.JpaRoleEntity;\nimport org.keycloak.models.map.storage.jpa.updater.MapJpaUpdaterProvider;\n@@ -185,9 +187,13 @@ public class JpaMapStorageProviderFactory implements\nfinal EventListenerRegistry eventListenerRegistry =\nsessionFactoryServiceRegistry.getService( EventListenerRegistry.class );\n- eventListenerRegistry.appendListeners(EventType.PRE_INSERT, JpaChildEntityListener.INSTANCE);\n- eventListenerRegistry.appendListeners(EventType.PRE_UPDATE, JpaChildEntityListener.INSTANCE);\n- eventListenerRegistry.appendListeners(EventType.PRE_DELETE, JpaChildEntityListener.INSTANCE);\n+ eventListenerRegistry.appendListeners(EventType.PRE_INSERT, JpaOptimisticLockingListener.INSTANCE);\n+ eventListenerRegistry.appendListeners(EventType.PRE_UPDATE, JpaOptimisticLockingListener.INSTANCE);\n+ eventListenerRegistry.appendListeners(EventType.PRE_DELETE, JpaOptimisticLockingListener.INSTANCE);\n+\n+ eventListenerRegistry.appendListeners(EventType.PRE_INSERT, JpaEntityVersionListener.INSTANCE);\n+ eventListenerRegistry.appendListeners(EventType.PRE_UPDATE, JpaEntityVersionListener.INSTANCE);\n+ eventListenerRegistry.appendListeners(EventType.PRE_DELETE, JpaEntityVersionListener.INSTANCE);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaRootEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaRootEntity.java", "diff": "package org.keycloak.models.map.storage.jpa;\nimport java.io.Serializable;\n+import java.util.Objects;\nimport org.keycloak.models.map.common.AbstractEntity;\n@@ -39,4 +40,25 @@ public interface JpaRootEntity extends AbstractEntity, Serializable {\n* @param entityVersion sets current supported version to JPA entity.\n*/\nvoid setEntityVersion(Integer entityVersion);\n+\n+ /**\n+ * In case of any update on entity, we want to update the entityVersion\n+ * to current one.\n+ * This includes downgrading from a future version of Keycloak, as the entityVersion must match the JSON\n+ * and the additional tables this version writes.\n+ *\n+ * The listener {@link org.keycloak.models.map.storage.jpa.hibernate.listeners.JpaEntityVersionListener}\n+ * calls this method whenever the root entity or one of its children changes.\n+ *\n+ * Future versions of this method might restrict downgrading to downgrade only from the next version.\n+ */\n+ default void updateEntityVersion() {\n+ Integer ev = getEntityVersion();\n+ Integer currentEv = getCurrentSchemaVersion();\n+ if (ev != null && !Objects.equals(ev, currentEv)) {\n+ setEntityVersion(currentEv);\n+ }\n+ }\n+\n+ Integer getCurrentSchemaVersion();\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "diff": "@@ -129,17 +129,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\nreturn metadata != null;\n}\n- /**\n- * In case of any update on entity, we want to update the entityVerion\n- * to current one.\n- */\n- private void checkEntityVersionForUpdate() {\n- Integer ev = getEntityVersion();\n- if (ev != null && ev < CURRENT_SCHEMA_VERSION_CLIENT) {\n- setEntityVersion(CURRENT_SCHEMA_VERSION_CLIENT);\n- }\n- }\n-\n@Override\npublic Integer getEntityVersion() {\nif (isMetadataInitialized()) return metadata.getEntityVersion();\n@@ -151,6 +140,11 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\nmetadata.setEntityVersion(entityVersion);\n}\n+ @Override\n+ public Integer getCurrentSchemaVersion() {\n+ return CURRENT_SCHEMA_VERSION_CLIENT;\n+ }\n+\n@Override\npublic int getVersion() {\nreturn version;\n@@ -174,7 +168,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setRealmId(String realmId) {\n- checkEntityVersionForUpdate();\nmetadata.setRealmId(realmId);\n}\n@@ -186,13 +179,11 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setClientId(String clientId) {\n- checkEntityVersionForUpdate();\nmetadata.setClientId(clientId);\n}\n@Override\npublic void setEnabled(Boolean enabled) {\n- checkEntityVersionForUpdate();\nmetadata.setEnabled(enabled);\n}\n@@ -209,13 +200,11 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setClientScope(String id, Boolean defaultScope) {\n- checkEntityVersionForUpdate();\nmetadata.setClientScope(id, defaultScope);\n}\n@Override\npublic void removeClientScope(String id) {\n- checkEntityVersionForUpdate();\nmetadata.removeClientScope(id);\n}\n@@ -231,19 +220,16 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void removeProtocolMapper(String id) {\n- checkEntityVersionForUpdate();\nmetadata.removeProtocolMapper(id);\n}\n@Override\npublic void setProtocolMapper(String id, MapProtocolMapperEntity mapping) {\n- checkEntityVersionForUpdate();\nmetadata.setProtocolMapper(id, mapping);\n}\n@Override\npublic void addRedirectUri(String redirectUri) {\n- checkEntityVersionForUpdate();\nmetadata.addRedirectUri(redirectUri);\n}\n@@ -254,25 +240,21 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void removeRedirectUri(String redirectUri) {\n- checkEntityVersionForUpdate();\nmetadata.removeRedirectUri(redirectUri);\n}\n@Override\npublic void setRedirectUris(Set<String> redirectUris) {\n- checkEntityVersionForUpdate();\nmetadata.setRedirectUris(redirectUris);\n}\n@Override\npublic void addScopeMapping(String id) {\n- checkEntityVersionForUpdate();\nmetadata.addScopeMapping(id);\n}\n@Override\npublic void removeScopeMapping(String id) {\n- checkEntityVersionForUpdate();\nmetadata.removeScopeMapping(id);\n}\n@@ -283,7 +265,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void addWebOrigin(String webOrigin) {\n- checkEntityVersionForUpdate();\nmetadata.addWebOrigin(webOrigin);\n}\n@@ -294,13 +275,11 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void removeWebOrigin(String webOrigin) {\n- checkEntityVersionForUpdate();\nmetadata.removeWebOrigin(webOrigin);\n}\n@Override\npublic void setWebOrigins(Set<String> webOrigins) {\n- checkEntityVersionForUpdate();\nmetadata.setWebOrigins(webOrigins);\n}\n@@ -316,13 +295,11 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void removeAuthenticationFlowBindingOverride(String binding) {\n- checkEntityVersionForUpdate();\nmetadata.removeAuthenticationFlowBindingOverride(binding);\n}\n@Override\npublic void setAuthenticationFlowBindingOverride(String binding, String flowId) {\n- checkEntityVersionForUpdate();\nmetadata.setAuthenticationFlowBindingOverride(binding, flowId);\n}\n@@ -333,7 +310,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setBaseUrl(String baseUrl) {\n- checkEntityVersionForUpdate();\nmetadata.setBaseUrl(baseUrl);\n}\n@@ -344,7 +320,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setClientAuthenticatorType(String clientAuthenticatorType) {\n- checkEntityVersionForUpdate();\nmetadata.setClientAuthenticatorType(clientAuthenticatorType);\n}\n@@ -355,7 +330,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setDescription(String description) {\n- checkEntityVersionForUpdate();\nmetadata.setDescription(description);\n}\n@@ -366,7 +340,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setManagementUrl(String managementUrl) {\n- checkEntityVersionForUpdate();\nmetadata.setManagementUrl(managementUrl);\n}\n@@ -377,7 +350,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setName(String name) {\n- checkEntityVersionForUpdate();\nmetadata.setName(name);\n}\n@@ -388,7 +360,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setNodeReRegistrationTimeout(Integer nodeReRegistrationTimeout) {\n- checkEntityVersionForUpdate();\nmetadata.setNodeReRegistrationTimeout(nodeReRegistrationTimeout);\n}\n@@ -399,7 +370,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setNotBefore(Integer notBefore) {\n- checkEntityVersionForUpdate();\nmetadata.setNotBefore(notBefore);\n}\n@@ -411,7 +381,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setProtocol(String protocol) {\n- checkEntityVersionForUpdate();\nmetadata.setProtocol(protocol);\n}\n@@ -422,7 +391,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setRegistrationToken(String registrationToken) {\n- checkEntityVersionForUpdate();\nmetadata.setRegistrationToken(registrationToken);\n}\n@@ -433,7 +401,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setRootUrl(String rootUrl) {\n- checkEntityVersionForUpdate();\nmetadata.setRootUrl(rootUrl);\n}\n@@ -444,7 +411,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setScope(Set<String> scope) {\n- checkEntityVersionForUpdate();\nmetadata.setScope(scope);\n}\n@@ -455,7 +421,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setSecret(String secret) {\n- checkEntityVersionForUpdate();\nmetadata.setSecret(secret);\n}\n@@ -466,7 +431,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setAlwaysDisplayInConsole(Boolean alwaysDisplayInConsole) {\n- checkEntityVersionForUpdate();\nmetadata.setAlwaysDisplayInConsole(alwaysDisplayInConsole);\n}\n@@ -477,7 +441,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setBearerOnly(Boolean bearerOnly) {\n- checkEntityVersionForUpdate();\nmetadata.setBearerOnly(bearerOnly);\n}\n@@ -488,7 +451,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setConsentRequired(Boolean consentRequired) {\n- checkEntityVersionForUpdate();\nmetadata.setConsentRequired(consentRequired);\n}\n@@ -499,7 +461,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setDirectAccessGrantsEnabled(Boolean directAccessGrantsEnabled) {\n- checkEntityVersionForUpdate();\nmetadata.setDirectAccessGrantsEnabled(directAccessGrantsEnabled);\n}\n@@ -510,7 +471,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setFrontchannelLogout(Boolean frontchannelLogout) {\n- checkEntityVersionForUpdate();\nmetadata.setFrontchannelLogout(frontchannelLogout);\n}\n@@ -521,7 +481,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setFullScopeAllowed(Boolean fullScopeAllowed) {\n- checkEntityVersionForUpdate();\nmetadata.setFullScopeAllowed(fullScopeAllowed);\n}\n@@ -532,7 +491,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setImplicitFlowEnabled(Boolean implicitFlowEnabled) {\n- checkEntityVersionForUpdate();\nmetadata.setImplicitFlowEnabled(implicitFlowEnabled);\n}\n@@ -543,7 +501,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setPublicClient(Boolean publicClient) {\n- checkEntityVersionForUpdate();\nmetadata.setPublicClient(publicClient);\n}\n@@ -554,7 +511,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setServiceAccountsEnabled(Boolean serviceAccountsEnabled) {\n- checkEntityVersionForUpdate();\nmetadata.setServiceAccountsEnabled(serviceAccountsEnabled);\n}\n@@ -565,7 +521,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setStandardFlowEnabled(Boolean standardFlowEnabled) {\n- checkEntityVersionForUpdate();\nmetadata.setStandardFlowEnabled(standardFlowEnabled);\n}\n@@ -576,13 +531,11 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setSurrogateAuthRequired(Boolean surrogateAuthRequired) {\n- checkEntityVersionForUpdate();\nmetadata.setSurrogateAuthRequired(surrogateAuthRequired);\n}\n@Override\npublic void removeAttribute(String name) {\n- checkEntityVersionForUpdate();\nfor (Iterator<JpaClientAttributeEntity> iterator = attributes.iterator(); iterator.hasNext();) {\nJpaClientAttributeEntity attr = iterator.next();\nif (Objects.equals(attr.getName(), name)) {\n@@ -593,7 +546,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setAttribute(String name, List<String> values) {\n- checkEntityVersionForUpdate();\nremoveAttribute(name);\nfor (String value : values) {\nJpaClientAttributeEntity attribute = new JpaClientAttributeEntity(this, name, value);\n@@ -622,7 +574,6 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Override\npublic void setAttributes(Map<String, List<String>> attributes) {\n- checkEntityVersionForUpdate();\nfor (Iterator<JpaClientAttributeEntity> iterator = this.attributes.iterator(); iterator.hasNext();) {\niterator.remove();\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "diff": "@@ -113,17 +113,6 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\nreturn metadata != null;\n}\n- /**\n- * In case of any update on entity, we want to update the entityVerion\n- * to current one.\n- */\n- private void checkEntityVersionForUpdate() {\n- Integer ev = getEntityVersion();\n- if (ev != null && ev < CURRENT_SCHEMA_VERSION_CLIENT_SCOPE) {\n- setEntityVersion(CURRENT_SCHEMA_VERSION_CLIENT_SCOPE);\n- }\n- }\n-\n@Override\npublic Integer getEntityVersion() {\nif (isMetadataInitialized()) return metadata.getEntityVersion();\n@@ -135,6 +124,11 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\nmetadata.setEntityVersion(entityVersion);\n}\n+ @Override\n+ public Integer getCurrentSchemaVersion() {\n+ return CURRENT_SCHEMA_VERSION_CLIENT_SCOPE;\n+ }\n+\n@Override\npublic int getVersion() {\nreturn version;\n@@ -158,7 +152,6 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Override\npublic void setRealmId(String realmId) {\n- checkEntityVersionForUpdate();\nmetadata.setRealmId(realmId);\n}\n@@ -169,19 +162,16 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Override\npublic void addProtocolMapper(MapProtocolMapperEntity mapping) {\n- checkEntityVersionForUpdate();\nmetadata.addProtocolMapper(mapping);\n}\n@Override\npublic void addScopeMapping(String id) {\n- checkEntityVersionForUpdate();\nmetadata.addScopeMapping(id);\n}\n@Override\npublic void removeScopeMapping(String id) {\n- checkEntityVersionForUpdate();\nmetadata.removeScopeMapping(id);\n}\n@@ -197,7 +187,6 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Override\npublic void setDescription(String description) {\n- checkEntityVersionForUpdate();\nmetadata.setDescription(description);\n}\n@@ -209,7 +198,6 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Override\npublic void setName(String name) {\n- checkEntityVersionForUpdate();\nmetadata.setName(name);\n}\n@@ -220,13 +208,11 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Override\npublic void setProtocol(String protocol) {\n- checkEntityVersionForUpdate();\nmetadata.setProtocol(protocol);\n}\n@Override\npublic void removeAttribute(String name) {\n- checkEntityVersionForUpdate();\nfor (Iterator<JpaClientScopeAttributeEntity> iterator = attributes.iterator(); iterator.hasNext();) {\nJpaClientScopeAttributeEntity attr = iterator.next();\nif (Objects.equals(attr.getName(), name)) {\n@@ -237,7 +223,6 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Override\npublic void setAttribute(String name, List<String> values) {\n- checkEntityVersionForUpdate();\nremoveAttribute(name);\nfor (String value : values) {\nJpaClientScopeAttributeEntity attribute = new JpaClientScopeAttributeEntity(this, name, value);\n@@ -266,7 +251,6 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Override\npublic void setAttributes(Map<String, List<String>> attributes) {\n- checkEntityVersionForUpdate();\nfor (Iterator<JpaClientScopeAttributeEntity> iterator = this.attributes.iterator(); iterator.hasNext();) {\niterator.remove();\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaEntityVersionListener.java", "diff": "+/*\n+ * Copyright 2022. Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.models.map.storage.jpa.hibernate.listeners;\n+\n+import org.hibernate.HibernateException;\n+import org.hibernate.event.spi.PreDeleteEvent;\n+import org.hibernate.event.spi.PreDeleteEventListener;\n+import org.hibernate.event.spi.PreInsertEvent;\n+import org.hibernate.event.spi.PreInsertEventListener;\n+import org.hibernate.event.spi.PreUpdateEvent;\n+import org.hibernate.event.spi.PreUpdateEventListener;\n+import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n+import org.keycloak.models.map.storage.jpa.JpaRootEntity;\n+\n+/**\n+ * Listen on changes on child- and root entities and updates the current entity version of the root.\n+ *\n+ * This support a multiple level parent-child relationship, where the upmost parent needs the entity version to be updated.\n+ */\n+public class JpaEntityVersionListener implements PreInsertEventListener, PreDeleteEventListener, PreUpdateEventListener {\n+\n+ public static final JpaEntityVersionListener INSTANCE = new JpaEntityVersionListener();\n+\n+ /**\n+ * Traverse from current entity up to the upmost parent, then update the entity version if it is a root entity.\n+ */\n+ public void updateEntityVersion(Object entity) throws HibernateException {\n+ Object root = entity;\n+ while(root instanceof JpaChildEntity) {\n+ root = ((JpaChildEntity<?>) entity).getParent();\n+ }\n+ if (root instanceof JpaRootEntity) {\n+ ((JpaRootEntity) root).updateEntityVersion();\n+ }\n+ }\n+\n+ @Override\n+ public boolean onPreInsert(PreInsertEvent event) {\n+ updateEntityVersion(event.getEntity());\n+ return false;\n+ }\n+\n+ @Override\n+ public boolean onPreDelete(PreDeleteEvent event) {\n+ updateEntityVersion(event.getEntity());\n+ return false;\n+ }\n+\n+ @Override\n+ public boolean onPreUpdate(PreUpdateEvent event) {\n+ updateEntityVersion(event.getEntity());\n+ return false;\n+ }\n+}\n" }, { "change_type": "RENAME", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaChildEntityListener.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaOptimisticLockingListener.java", "diff": "* limitations under the License.\n*/\n-package org.keycloak.models.map.storage.jpa;\n+package org.keycloak.models.map.storage.jpa.hibernate.listeners;\nimport org.hibernate.HibernateException;\nimport org.hibernate.Session;\n@@ -25,22 +25,23 @@ import org.hibernate.event.spi.PreInsertEvent;\nimport org.hibernate.event.spi.PreInsertEventListener;\nimport org.hibernate.event.spi.PreUpdateEvent;\nimport org.hibernate.event.spi.PreUpdateEventListener;\n+import org.keycloak.models.map.storage.jpa.JpaChildEntity;\nimport javax.persistence.LockModeType;\n/**\n- * Listen on changes on child entities and forces an optimistic locking increment on the topmost parent.\n+ * Listen on changes on child entities and forces an optimistic locking increment on the topmost parent aka root.\n*\n* This support a multiple level parent-child relationship, where only the upmost parent is locked.\n*/\n-public class JpaChildEntityListener implements PreInsertEventListener, PreDeleteEventListener, PreUpdateEventListener {\n+public class JpaOptimisticLockingListener implements PreInsertEventListener, PreDeleteEventListener, PreUpdateEventListener {\n- public static final JpaChildEntityListener INSTANCE = new JpaChildEntityListener();\n+ public static final JpaOptimisticLockingListener INSTANCE = new JpaOptimisticLockingListener();\n/**\n- * Check if the entity is a child with a parent and force optimistic locking increment on the upmost parent.\n+ * Check if the entity is a child with a parent and force optimistic locking increment on the upmost parent aka root.\n*/\n- public void checkRoot(Session session, Object entity) throws HibernateException {\n+ public void lockRootEntity(Session session, Object entity) throws HibernateException {\nif(entity instanceof JpaChildEntity) {\nObject root = entity;\nwhile (root instanceof JpaChildEntity) {\n@@ -52,19 +53,19 @@ public class JpaChildEntityListener implements PreInsertEventListener, PreDelete\n@Override\npublic boolean onPreInsert(PreInsertEvent event) {\n- checkRoot(event.getSession(), event.getEntity());\n+ lockRootEntity(event.getSession(), event.getEntity());\nreturn false;\n}\n@Override\npublic boolean onPreDelete(PreDeleteEvent event) {\n- checkRoot(event.getSession(), event.getEntity());\n+ lockRootEntity(event.getSession(), event.getEntity());\nreturn false;\n}\n@Override\npublic boolean onPreUpdate(PreUpdateEvent event) {\n- checkRoot(event.getSession(), event.getEntity());\n+ lockRootEntity(event.getSession(), event.getEntity());\nreturn false;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "diff": "@@ -121,15 +121,9 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\nreturn metadata != null;\n}\n- /**\n- * In case of any update on entity, we want to update the entityVerion\n- * to current one.\n- */\n- private void checkEntityVersionForUpdate() {\n- Integer ev = getEntityVersion();\n- if (ev != null && ev < CURRENT_SCHEMA_VERSION_ROLE) {\n- setEntityVersion(CURRENT_SCHEMA_VERSION_ROLE);\n- }\n+ @Override\n+ public Integer getCurrentSchemaVersion() {\n+ return CURRENT_SCHEMA_VERSION_ROLE;\n}\n@Override\n@@ -189,25 +183,21 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\n@Override\npublic void setRealmId(String realmId) {\n- checkEntityVersionForUpdate();\nmetadata.setRealmId(realmId);\n}\n@Override\npublic void setClientId(String clientId) {\n- checkEntityVersionForUpdate();\nmetadata.setClientId(clientId);\n}\n@Override\npublic void setName(String name) {\n- checkEntityVersionForUpdate();\nmetadata.setName(name);\n}\n@Override\npublic void setDescription(String description) {\n- checkEntityVersionForUpdate();\nmetadata.setDescription(description);\n}\n@@ -218,19 +208,16 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\n@Override\npublic void setCompositeRoles(Set<String> compositeRoles) {\n- checkEntityVersionForUpdate();\nmetadata.setCompositeRoles(compositeRoles);\n}\n@Override\npublic void addCompositeRole(String roleId) {\n- checkEntityVersionForUpdate();\nmetadata.addCompositeRole(roleId);\n}\n@Override\npublic void removeCompositeRole(String roleId) {\n- checkEntityVersionForUpdate();\nmetadata.removeCompositeRole(roleId);\n}\n@@ -255,7 +242,6 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\n@Override\npublic void setAttributes(Map<String, List<String>> attributes) {\n- checkEntityVersionForUpdate();\nfor (Iterator<JpaRoleAttributeEntity> iterator = this.attributes.iterator(); iterator.hasNext();) {\niterator.remove();\n}\n@@ -268,7 +254,6 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\n@Override\npublic void setAttribute(String name, List<String> values) {\n- checkEntityVersionForUpdate();\nremoveAttribute(name);\nfor (String value : values) {\nJpaRoleAttributeEntity attribute = new JpaRoleAttributeEntity(this, name, value);\n@@ -278,7 +263,6 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\n@Override\npublic void removeAttribute(String name) {\n- checkEntityVersionForUpdate();\nfor (Iterator<JpaRoleAttributeEntity> iterator = attributes.iterator(); iterator.hasNext();) {\nJpaRoleAttributeEntity attr = iterator.next();\nif (Objects.equals(attr.getName(), name)) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Update the entityVersion also for downgrades, as it needs to match the JSON and auxiliary tables. Will trigger also when changes to a child occur, like for example when attributes change. Closes #9716
339,410
07.02.2022 20:47:03
-3,600
100dbb8781d780d35ad0569222bcda3ef85bbe0a
Rework escaping of special characters in message properties for account console Closes
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java", "new_path": "services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java", "diff": "@@ -168,10 +168,11 @@ public class AccountConsole {\n}\nprivate String convertPropValue(String propertyValue) {\n- propertyValue = propertyValue.replace(\"''\", \"%27\");\n- propertyValue = propertyValue.replace(\"'\", \"%27\");\n- propertyValue = propertyValue.replace(\"\\\"\", \"%22\");\n-\n+ // this mimics the behavior of java.text.MessageFormat used for the freemarker templates:\n+ // To print a single quote one needs to write two single quotes.\n+ // Single quotes will be stripped.\n+ // Usually single quotes would escape parameters, but this not implemented here.\n+ propertyValue = propertyValue.replaceAll(\"'('?)\", \"$1\");\npropertyValue = putJavaParamsInNgTranslateFormat(propertyValue);\nreturn propertyValue;\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak.v2/account/index.ftl", "new_path": "themes/src/main/resources/theme/keycloak.v2/account/index.ftl", "diff": "<#if msg??>\nvar locale = '${locale}';\n- var l18nMsg = JSON.parse('${msgJSON?no_esc}');\n+ <#outputformat \"JavaScript\">\n+ var l18nMsg = JSON.parse('${msgJSON?js_string}');\n+ </#outputformat>\n<#else>\nvar locale = 'en';\nvar l18Msg = {};\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak.v2/account/src/app/widgets/Msg.tsx", "new_path": "themes/src/main/resources/theme/keycloak.v2/account/src/app/widgets/Msg.tsx", "diff": "@@ -58,7 +58,7 @@ export class Msg extends React.Component<MsgProps> {\n})\n}\n- return unescape(message);\n+ return message;\n}\n// if the message key has Freemarker syntax, remove it\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Rework escaping of special characters in message properties for account console (#9995) Closes #9503
339,707
08.02.2022 08:35:31
10,800
d1b64f47fa67a926dfb576e0d1c3544ce7cfdfdd
Update Portuguese (Brazil) translations
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources-community/theme/base/login/messages/messages_pt_BR.properties", "new_path": "themes/src/main/resources-community/theme/base/login/messages/messages_pt_BR.properties", "diff": "@@ -31,7 +31,7 @@ realmChoice=Dom\\u00EDnio\nunknownUser=Usu\\u00E1rio desconhecido\nloginTotpTitle=Configura\\u00E7\\u00E3o do autenticador m\\u00f3vel\nloginProfileTitle=Atualizar Informa\\u00E7\\u00F5es da Conta\n-loginTimeout=Voc\\u00EA demorou muito para entrar. Por favor, recome\\u00e7e o processo de login.\n+loginTimeout=Voc\\u00EA demorou muito para entrar. Por favor, recomece o processo de login.\noauthGrantTitle=Conceder acesso a {0}\noauthGrantTitleHtml={0}\nerrorTitle=Sentimos muito...\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Update Portuguese (Brazil) translations #9892 (#9893)
339,410
03.02.2022 14:47:39
-3,600
45df1adba912c08a1b7cc203c362abae7a33790c
Update generics in JPA Map storage to avoid casting and compiler warnings Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaModelCriteriaBuilder.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaModelCriteriaBuilder.java", "diff": "@@ -36,7 +36,7 @@ import org.keycloak.storage.SearchableModelField;\n* @param <M> Model\n* @param <Self> specific implementation of this class\n*/\n-public abstract class JpaModelCriteriaBuilder<E, M, Self extends ModelCriteriaBuilder<M, Self>> implements ModelCriteriaBuilder<M, Self> {\n+public abstract class JpaModelCriteriaBuilder<E, M, Self extends JpaModelCriteriaBuilder<E, M, Self>> implements ModelCriteriaBuilder<M, Self> {\nprivate final Function<BiFunction<CriteriaBuilder, Root<E>, Predicate>, Self> instantiator;\nprivate BiFunction<CriteriaBuilder, Root<E>, Predicate> predicateFunc = null;\n@@ -51,7 +51,7 @@ public abstract class JpaModelCriteriaBuilder<E, M, Self extends ModelCriteriaBu\nthis.predicateFunc = predicateFunc;\n}\n- protected void validateValue(Object[] value, SearchableModelField field, ModelCriteriaBuilder.Operator op, Class<?>... expectedTypes) {\n+ protected void validateValue(Object[] value, SearchableModelField<? super M> field, ModelCriteriaBuilder.Operator op, Class<?>... expectedTypes) {\nif (value == null || expectedTypes == null || value.length != expectedTypes.length) {\nthrow new CriterionNotSupportedException(field, op, \"Invalid argument: \" + Arrays.toString(value));\n}\n@@ -71,29 +71,21 @@ public abstract class JpaModelCriteriaBuilder<E, M, Self extends ModelCriteriaBu\n}\n}\n+ @SafeVarargs\n@Override\n- public Self and(Self... builders) {\n- return instantiator.apply((cb, root) -> cb.and(Stream.of(builders).map((Self b) -> {\n- if ( !(b instanceof JpaModelCriteriaBuilder)) throw new IllegalStateException(\"Invalid type of ModelCriteriaBuilder.\");\n- return ((JpaModelCriteriaBuilder) b).getPredicateFunc().apply(cb, root);\n- }).toArray(Predicate[]::new)));\n+ public final Self and(Self... builders) {\n+ return instantiator.apply((cb, root) -> cb.and(Stream.of(builders).map((Self b) -> b.getPredicateFunc().apply(cb, root)).toArray(Predicate[]::new)));\n}\n+ @SafeVarargs\n@Override\n- public Self or(Self... builders) {\n- return instantiator.apply((cb, root) -> cb.or(Stream.of(builders).map((Self b) -> {\n- if ( !(b instanceof JpaModelCriteriaBuilder)) throw new IllegalStateException(\"Invalid type of ModelCriteriaBuilder.\");\n- return ((JpaModelCriteriaBuilder) b).getPredicateFunc().apply(cb, root);\n- }).toArray(Predicate[]::new)));\n+ public final Self or(Self... builders) {\n+ return instantiator.apply((cb, root) -> cb.or(Stream.of(builders).map((Self b) -> (b).getPredicateFunc().apply(cb, root)).toArray(Predicate[]::new)));\n}\n@Override\npublic Self not(Self builder) {\n- return instantiator.apply((cb, root) -> {\n- if ( !(builder instanceof JpaModelCriteriaBuilder)) throw new IllegalStateException(\"Invalid type of ModelCriteriaBuilder.\");\n- BiFunction<CriteriaBuilder, Root<E>, Predicate> predFunc = ((JpaModelCriteriaBuilder) builder).getPredicateFunc();\n- return cb.not(predFunc.apply(cb, root));\n- });\n+ return instantiator.apply((cb, root) -> cb.not(builder.getPredicateFunc().apply(cb, root)));\n}\npublic BiFunction<CriteriaBuilder, Root<E>, Predicate> getPredicateFunc() {\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/storage/ModelCriteriaBuilder.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/storage/ModelCriteriaBuilder.java", "diff": "@@ -96,7 +96,7 @@ public interface ModelCriteriaBuilder<M, Self extends ModelCriteriaBuilder<M, Se\nILIKE,\n/**\n* Operator for belonging into a collection of values. Operand in {@code value}\n- * can be an array (via an implicit conversion of the vararg), a {@link Collection} or a {@link Stream}.\n+ * can be an array (via an implicit conversion of the vararg), a {@link java.util.Collection} or a {@link java.util.stream.Stream}.\n*/\nIN,\n/** Is not null and, in addition, in case of collection not empty */\n@@ -115,7 +115,7 @@ public interface ModelCriteriaBuilder<M, Self extends ModelCriteriaBuilder<M, Se\n* @param op Operator\n* @param value Additional operands of the operator.\n* @return\n- * @throws CriterionNotSupported If the operator is not supported for the given field.\n+ * @throws CriterionNotSupportedException If the operator is not supported for the given field.\n*/\nSelf compare(SearchableModelField<? super M> modelField, Operator op, Object... value);\n@@ -134,8 +134,9 @@ public interface ModelCriteriaBuilder<M, Self extends ModelCriteriaBuilder<M, Se\n* );\n* </pre>\n*\n- * @throws CriterionNotSupported If the operator is not supported for the given field.\n+ * @throws CriterionNotSupportedException If the operator is not supported for the given field.\n*/\n+ @SuppressWarnings(\"unchecked\")\nSelf and(Self... builders);\n/**\n@@ -153,8 +154,9 @@ public interface ModelCriteriaBuilder<M, Self extends ModelCriteriaBuilder<M, Se\n* );\n* </pre>\n*\n- * @throws CriterionNotSupported If the operator is not supported for the given field.\n+ * @throws CriterionNotSupportedException If the operator is not supported for the given field.\n*/\n+ @SuppressWarnings(\"unchecked\")\nSelf or(Self... builders);\n/**\n@@ -166,7 +168,7 @@ public interface ModelCriteriaBuilder<M, Self extends ModelCriteriaBuilder<M, Se\n*\n* @param builder\n* @return\n- * @throws CriterionNotSupported If the operator is not supported for the given field.\n+ * @throws CriterionNotSupportedException If the operator is not supported for the given field.\n*/\nSelf not(Self builder);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Update generics in JPA Map storage to avoid casting and compiler warnings Closes #10060
339,281
08.02.2022 15:54:48
-3,600
844c210d86149ae16391794c7829da3fe4c5c83e
Create common parent for Jpa*AttributeEntity Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaAttributeEntity.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.keycloak.models.map.storage.jpa;\n+\n+import java.util.Objects;\n+import java.util.UUID;\n+import javax.persistence.Column;\n+import javax.persistence.FetchType;\n+import javax.persistence.GeneratedValue;\n+import javax.persistence.Id;\n+import javax.persistence.JoinColumn;\n+import javax.persistence.ManyToOne;\n+import javax.persistence.MappedSuperclass;\n+import org.hibernate.annotations.Nationalized;\n+\n+@MappedSuperclass\n+public abstract class JpaAttributeEntity<E> implements JpaChildEntity<E> {\n+\n+ @Id\n+ @Column\n+ @GeneratedValue\n+ private UUID id;\n+\n+ @ManyToOne(fetch = FetchType.LAZY)\n+ @JoinColumn(name=\"fk_root\")\n+ private E root;\n+\n+ @Column\n+ private String name;\n+\n+ @Nationalized\n+ @Column\n+ private String value;\n+\n+ public JpaAttributeEntity() {\n+ }\n+\n+ public JpaAttributeEntity(E root, String name, String value) {\n+ this.root = root;\n+ this.name = name;\n+ this.value = value;\n+ }\n+\n+ public UUID getId() {\n+ return id;\n+ }\n+\n+ public String getName() {\n+ return name;\n+ }\n+\n+ public void setName(String name) {\n+ this.name = name;\n+ }\n+\n+ public String getValue() {\n+ return value;\n+ }\n+\n+ public void setValue(String value) {\n+ this.value = value;\n+ }\n+\n+ @Override\n+ public E getParent() {\n+ return root;\n+ }\n+\n+ public void setParent(E root) {\n+ this.root = root;\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return getClass().hashCode();\n+ }\n+\n+ @Override\n+ public boolean equals(Object obj) {\n+ if (this == obj) return true;\n+ if (!(obj instanceof JpaAttributeEntity)) return false;\n+ JpaAttributeEntity<?> that = (JpaAttributeEntity<?>) obj;\n+ return Objects.equals(getParent(), that.getParent()) &&\n+ Objects.equals(getName(), that.getName()) &&\n+ Objects.equals(getValue(), that.getValue());\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "diff": "*/\npackage org.keycloak.models.map.storage.jpa.client.entity;\n-import java.util.Objects;\n-import java.util.UUID;\n-import javax.persistence.Column;\nimport javax.persistence.Entity;\n-import javax.persistence.FetchType;\n-import javax.persistence.GeneratedValue;\n-import javax.persistence.Id;\n-import javax.persistence.JoinColumn;\n-import javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n-import org.hibernate.annotations.Nationalized;\n-import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n+import org.keycloak.models.map.storage.jpa.JpaAttributeEntity;\n@Entity\n@Table(name = \"client_attribute\")\n-public class JpaClientAttributeEntity implements JpaChildEntity<JpaClientEntity> {\n-\n- @Id\n- @Column\n- @GeneratedValue\n- private UUID id;\n-\n- @ManyToOne(fetch = FetchType.LAZY)\n- @JoinColumn(name=\"fk_client\")\n- private JpaClientEntity client;\n-\n- @Column\n- private String name;\n-\n- @Nationalized\n- @Column\n- private String value;\n+public class JpaClientAttributeEntity extends JpaAttributeEntity<JpaClientEntity> {\npublic JpaClientAttributeEntity() {\n}\n- public JpaClientAttributeEntity(JpaClientEntity client, String name, String value) {\n- this.client = client;\n- this.name = name;\n- this.value = value;\n- }\n-\n- public UUID getId() {\n- return id;\n- }\n-\n- public JpaClientEntity getClient() {\n- return client;\n- }\n-\n- public void setClient(JpaClientEntity client) {\n- this.client = client;\n- }\n-\n- public String getName() {\n- return name;\n- }\n-\n- public void setName(String name) {\n- this.name = name;\n- }\n-\n- public String getValue() {\n- return value;\n- }\n-\n- public void setValue(String value) {\n- this.value = value;\n- }\n-\n- @Override\n- public int hashCode() {\n- return getClass().hashCode();\n- }\n-\n- @Override\n- public boolean equals(Object obj) {\n- if (this == obj) return true;\n- if (!(obj instanceof JpaClientAttributeEntity)) return false;\n- JpaClientAttributeEntity that = (JpaClientAttributeEntity) obj;\n- return Objects.equals(getClient(), that.getClient()) &&\n- Objects.equals(getName(), that.getName()) &&\n- Objects.equals(getValue(), that.getValue());\n- }\n-\n- @Override\n- public JpaClientEntity getParent() {\n- return getClient();\n+ public JpaClientAttributeEntity(JpaClientEntity root, String name, String value) {\n+ super(root, name, value);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "diff": "@@ -95,7 +95,7 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootEnti\n@Basic(fetch = FetchType.LAZY)\nprivate Boolean enabled;\n- @OneToMany(mappedBy = \"client\", cascade = CascadeType.PERSIST, orphanRemoval = true)\n+ @OneToMany(mappedBy = \"root\", cascade = CascadeType.PERSIST, orphanRemoval = true)\nprivate final Set<JpaClientAttributeEntity> attributes = new HashSet<>();\n/**\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeAttributeEntity.java", "diff": "*/\npackage org.keycloak.models.map.storage.jpa.clientscope.entity;\n-import java.util.Objects;\n-import java.util.UUID;\n-import javax.persistence.Column;\nimport javax.persistence.Entity;\n-import javax.persistence.FetchType;\n-import javax.persistence.GeneratedValue;\n-import javax.persistence.Id;\n-import javax.persistence.JoinColumn;\n-import javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n-import org.hibernate.annotations.Nationalized;\n-import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n+import org.keycloak.models.map.storage.jpa.JpaAttributeEntity;\n@Entity\n@Table(name = \"client_scope_attribute\")\n-public class JpaClientScopeAttributeEntity implements JpaChildEntity<JpaClientScopeEntity> {\n-\n- @Id\n- @Column\n- @GeneratedValue\n- private UUID id;\n-\n- @ManyToOne(fetch = FetchType.LAZY)\n- @JoinColumn(name=\"fk_client_scope\")\n- private JpaClientScopeEntity clientScope;\n-\n- @Column\n- private String name;\n-\n- @Nationalized\n- @Column\n- private String value;\n+public class JpaClientScopeAttributeEntity extends JpaAttributeEntity<JpaClientScopeEntity> {\npublic JpaClientScopeAttributeEntity() {\n}\n- public JpaClientScopeAttributeEntity(JpaClientScopeEntity clientScope, String name, String value) {\n- this.clientScope = clientScope;\n- this.name = name;\n- this.value = value;\n- }\n-\n- public UUID getId() {\n- return id;\n- }\n-\n- public JpaClientScopeEntity getClientScope() {\n- return clientScope;\n- }\n-\n- public void setClientScope(JpaClientScopeEntity clientScope) {\n- this.clientScope = clientScope;\n- }\n-\n- public String getName() {\n- return name;\n- }\n-\n- public void setName(String name) {\n- this.name = name;\n- }\n-\n- public String getValue() {\n- return value;\n- }\n-\n- public void setValue(String value) {\n- this.value = value;\n- }\n-\n- @Override\n- public int hashCode() {\n- return getClass().hashCode();\n- }\n-\n- @Override\n- public boolean equals(Object obj) {\n- if (this == obj) return true;\n- if (!(obj instanceof JpaClientScopeAttributeEntity)) return false;\n- JpaClientScopeAttributeEntity that = (JpaClientScopeAttributeEntity) obj;\n- return Objects.equals(getClientScope(), that.getClientScope()) &&\n- Objects.equals(getName(), that.getName()) &&\n- Objects.equals(getValue(), that.getValue());\n- }\n-\n- @Override\n- public JpaClientScopeEntity getParent() {\n- return getClientScope();\n+ public JpaClientScopeAttributeEntity(JpaClientScopeEntity root, String name, String value) {\n+ super(root, name, value);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "diff": "@@ -82,7 +82,7 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J\n@Basic(fetch = FetchType.LAZY)\nprivate String name;\n- @OneToMany(mappedBy = \"clientScope\", cascade = CascadeType.PERSIST, orphanRemoval = true)\n+ @OneToMany(mappedBy = \"root\", cascade = CascadeType.PERSIST, orphanRemoval = true)\nprivate final Set<JpaClientScopeAttributeEntity> attributes = new HashSet<>();\n/**\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "diff": "*/\npackage org.keycloak.models.map.storage.jpa.role.entity;\n-import java.util.Objects;\n-import java.util.UUID;\n-import javax.persistence.Column;\nimport javax.persistence.Entity;\n-import javax.persistence.FetchType;\n-import javax.persistence.GeneratedValue;\n-import javax.persistence.Id;\n-import javax.persistence.JoinColumn;\n-import javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n-import org.hibernate.annotations.Nationalized;\n-import org.keycloak.models.map.storage.jpa.JpaChildEntity;\n+import org.keycloak.models.map.storage.jpa.JpaAttributeEntity;\n@Entity\n@Table(name = \"role_attribute\")\n-public class JpaRoleAttributeEntity implements JpaChildEntity<JpaRoleEntity> {\n-\n- @Id\n- @Column\n- @GeneratedValue\n- private UUID id;\n-\n- @ManyToOne(fetch = FetchType.LAZY)\n- @JoinColumn(name=\"fk_role\")\n- private JpaRoleEntity role;\n-\n- @Column\n- private String name;\n-\n- @Nationalized\n- @Column\n- private String value;\n+public class JpaRoleAttributeEntity extends JpaAttributeEntity<JpaRoleEntity> {\npublic JpaRoleAttributeEntity() {\n}\n- public JpaRoleAttributeEntity(JpaRoleEntity role, String name, String value) {\n- this.role = role;\n- this.name = name;\n- this.value = value;\n- }\n-\n- public UUID getId() {\n- return id;\n- }\n-\n- public JpaRoleEntity getRole() {\n- return role;\n- }\n-\n- public void setRole(JpaRoleEntity role) {\n- this.role = role;\n- }\n-\n- public String getName() {\n- return name;\n- }\n-\n- public void setName(String name) {\n- this.name = name;\n- }\n-\n- public String getValue() {\n- return value;\n- }\n-\n- public void setValue(String value) {\n- this.value = value;\n- }\n-\n- @Override\n- public int hashCode() {\n- return getClass().hashCode();\n- }\n-\n- @Override\n- public boolean equals(Object obj) {\n- if (this == obj) return true;\n- if (!(obj instanceof JpaRoleAttributeEntity)) return false;\n- JpaRoleAttributeEntity that = (JpaRoleAttributeEntity) obj;\n- return Objects.equals(getRole(), that.getRole()) &&\n- Objects.equals(getName(), that.getName()) &&\n- Objects.equals(getValue(), that.getValue());\n- }\n-\n- @Override\n- public JpaRoleEntity getParent() {\n- return role;\n+ public JpaRoleAttributeEntity(JpaRoleEntity root, String name, String value) {\n+ super(root, name, value);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "diff": "@@ -88,7 +88,7 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\n@Basic(fetch = FetchType.LAZY)\nprivate String description;\n- @OneToMany(mappedBy = \"role\", cascade = CascadeType.PERSIST, orphanRemoval = true)\n+ @OneToMany(mappedBy = \"root\", cascade = CascadeType.PERSIST, orphanRemoval = true)\nprivate final Set<JpaRoleAttributeEntity> attributes = new HashSet<>();\n/**\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/client-scopes/jpa-client-scopes-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/client-scopes/jpa-client-scopes-changelog-1.xml", "diff": "@@ -51,14 +51,14 @@ limitations under the License.\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n- <column name=\"fk_client_scope\" type=\"UUID\">\n- <constraints foreignKeyName=\"client_scope_attr_fk_client_scope_fkey\" references=\"client_scope(id)\" deleteCascade=\"true\"/>\n+ <column name=\"fk_root\" type=\"UUID\">\n+ <constraints foreignKeyName=\"client_scope_attr_fk_root_fkey\" references=\"client_scope(id)\" deleteCascade=\"true\"/>\n</column>\n<column name=\"name\" type=\"VARCHAR(255)\"/>\n<column name=\"value\" type=\"text\"/>\n</createTable>\n- <createIndex tableName=\"client_scope_attribute\" indexName=\"client_scope_attr_fk_client_scope\">\n- <column name=\"fk_client_scope\"/>\n+ <createIndex tableName=\"client_scope_attribute\" indexName=\"client_scope_attr_fk_root\">\n+ <column name=\"fk_root\"/>\n</createIndex>\n<createIndex tableName=\"client_scope_attribute\" indexName=\"client_scope_attr_name_value\">\n<column name=\"name\"/>\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "diff": "@@ -58,14 +58,14 @@ limitations under the License.\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n- <column name=\"fk_client\" type=\"UUID\">\n- <constraints foreignKeyName=\"client_attr_fk_client_fkey\" references=\"client(id)\" deleteCascade=\"true\"/>\n+ <column name=\"fk_root\" type=\"UUID\">\n+ <constraints foreignKeyName=\"client_attr_fk_root_fkey\" references=\"client(id)\" deleteCascade=\"true\"/>\n</column>\n<column name=\"name\" type=\"VARCHAR(255)\"/>\n<column name=\"value\" type=\"text\"/>\n</createTable>\n- <createIndex tableName=\"client_attribute\" indexName=\"client_attr_fk_client\">\n- <column name=\"fk_client\"/>\n+ <createIndex tableName=\"client_attribute\" indexName=\"client_attr_fk_root\">\n+ <column name=\"fk_root\"/>\n</createIndex>\n<createIndex tableName=\"client_attribute\" indexName=\"client_attr_name_value\">\n<column name=\"name\"/>\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/roles/jpa-roles-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/roles/jpa-roles-changelog-1.xml", "diff": "@@ -60,14 +60,14 @@ limitations under the License.\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n- <column name=\"fk_role\" type=\"UUID\">\n- <constraints foreignKeyName=\"role_attr_fk_role_fkey\" references=\"role(id)\" deleteCascade=\"true\"/>\n+ <column name=\"fk_root\" type=\"UUID\">\n+ <constraints foreignKeyName=\"role_attr_fk_root_fkey\" references=\"role(id)\" deleteCascade=\"true\"/>\n</column>\n<column name=\"name\" type=\"VARCHAR(255)\"/>\n<column name=\"value\" type=\"text\"/>\n</createTable>\n- <createIndex tableName=\"role_attribute\" indexName=\"role_attr_fk_role\">\n- <column name=\"fk_role\"/>\n+ <createIndex tableName=\"role_attribute\" indexName=\"role_attr_fk_root\">\n+ <column name=\"fk_root\"/>\n</createIndex>\n<createIndex tableName=\"role_attribute\" indexName=\"role_attr_name_value\">\n<column name=\"name\"/>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Create common parent for Jpa*AttributeEntity Closes #10071
339,618
07.02.2022 16:21:52
-3,600
1b7735816097e2a1794dd6926e5fbb74c15d5c95
Logging guide v1 Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/containers.adoc", "new_path": "docs/guides/src/main/server/containers.adoc", "diff": "@@ -88,7 +88,7 @@ podman|docker run --name keycloak_test -p 8080:8080 \\\nInvoking this command starts the Keycloak server in development mode.\nThis mode should be strictly avoided in production environments because it has insecure defaults.\n-For more information about running Keycloak in production, see _todo_link_to_running_in_production_guide_.\n+For more information about running Keycloak in production, take a look at the <@links.server id=\"configuration-production\"/> guide.\n== Use auto-build to run a standard keycloak container\nIn keeping with concepts such as immutable infrastructure, containers need to be re-provisioned routinely.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/guides/src/main/server/logging.adoc", "diff": "+<#import \"/templates/guide.adoc\" as tmpl>\n+<#import \"/templates/kc.adoc\" as kc>\n+<#import \"/templates/links.adoc\" as links>\n+\n+<@tmpl.guide\n+title=\"Configuring logging\"\n+summary=\"Learn how to configure Logging\"\n+includedOptions=\"log-*\">\n+\n+Logging is done on a per-category basis in Keycloak. You can configure logging for the root log level, or for more specific categories like `org.hibernate` or `org.keycloak`. In this guide, you will learn how to configure the log level and format.\n+\n+== Log level\n+The available log levels are listed in the following Table:\n+\n+|====\n+|Level|Description\n+|FATAL|critical failures / complete inability to serve requests of any kind.\n+|ERROR|significant error or problem leading to the inability to process requests.\n+|WARN|A non-critical error or problem that may not require immediate correction.\n+|INFO|Keycloak lifecycle events or important information. Low frequency.\n+|DEBUG|More detailed information for debugging purposes, including e.g. database logs. Higher frequency.\n+|TRACE|Most detailed debugging information. Very high frequency.\n+|ALL|Special level for all log messages\n+|OFF|Special level to turn logging off entirely (not recommended)\n+|====\n+\n+=== Configuring the root log level\n+The root loggers log level can be set using the following command:\n+\n+<@kc.start parameters=\"--log-level=<root-level>\"/>\n+\n+using one of the levels mentioned in the table above. When no log level configuration exists for a more specific category logger, the enclosing category is used instead. When there is no enclosing category, the root logger level is used.\n+\n+Setting the log level is case-insensitive, so you could either use for example `DEBUG` or `debug`.\n+\n+When you accidentally set the log level twice, for example when you invoke `--log-level=info,...,debug,...` the last occurence in the list will be used as the log level, so for the example the root logger would be set to `DEBUG`.\n+\n+=== Configuring category-specific log levels\n+It is possible to set a different log level for specific areas in Keycloak. To enable category-specific logging, provide a comma-separated list containing the categories you want another log level than for the root category to the `--log-level` configuration:\n+\n+<@kc.start parameters=\"--log-level=<root-level>,<org.category1>:<org.category1-level>\"/>\n+\n+A configuration that applies to a category also applies to all sub-categories of that category, unless a more specific matching sub-category configuration is provided in the list.\n+\n+.Example\n+<@kc.start parameters=\"--log-level=INFO,org.hibernate:debug,org.hibernate.hql.internal.ast:info\"/>\n+The example above sets the root log level for all loggers to INFO, and the hibernate log level in general to debug. But as we don't want SQL abstract syntax trees to make the log output verbose, we set the more specific sub category `org.hibernate.hql.internal.ast` to info, so the SQL abstract syntax trees, which would be shown at `debug` level, don't show up anymore.\n+\n+== Configuring the logging format\n+Keycloak uses a pattern-based logging formatter that generates human-readable text logs by default.\n+\n+The logging format template for these lines can be applied at the root level.\n+\n+The default format template is:\n+\n+* `%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n`\n+\n+The format string supports the following symbols:\n+\n+|====\n+|Symbol|Summary|Description\n+|%%|%|Renders a simple % character.\n+|%c|Category|Renders the log category name.\n+|%d{xxx}|Date|Renders a date with the given date format string.String syntax defined by `java.text.SimpleDateFormat`\n+|%e|Exception|Renders the thrown exception, if any.\n+|%h|Hostname|Renders the simple host name.\n+|%H|Qualified host name|Renders the fully qualified hostname, which may be the same as the simple host name, depending on the OS configuration.\n+|%i|Process ID|Renders the current process PID.\n+|%m|Full Message|Renders the log message plus exception (if any).\n+|%n |Newline|Renders the platform-specific line separator string.\n+|%N|Process name|Renders the name of the current process.\n+|%p|Level|Renders the log level of the message.\n+|%r|Relative time|Render the time in milliseconds since the start of the application log.\n+|%s|Simple message|Renders only the log message, without exception trace.\n+|%t|Thread name|Renders the thread name.\n+|%t{id}|Thread ID|Render the thread ID.\n+|%z{<zone name>}|Time zone|Set the time zone of log output to <zone name>.\n+|====\n+\n+=== Set the logging format\n+To set the logging format for a logged line, build your desired format template using the table above and run the following command:\n+<@kc.start parameters=\"--log-format=\\\"\\'<format>\\'\\\"\"/>\n+Be aware that you need to escape characters when invoking the command using the CLI, so you might want to set it in the configuration file instead.\n+\n+.Example: Abbreviate the fully qualified category name\n+<@kc.start parameters=\"\\\"\\'%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c{3.}] (%t) %s%e%n\\'\\\"\"/>\n+The example above abbreviates the category name, which could get rather long in some cases, to three characters by setting `[%c{3.}]` in the template instead of the default `[%c]`.\n+\n+== Configuring raw quarkus logging properties\n+At the time of writing, the logging features of the quarkus based Keycloak are basic, yet powerful. Nevertheless, expect more to come and feel free to join the https://github.com/keycloak/keycloak/discussions/8870[discussion] at GitHub.\n+\n+When you need a temporary solution, e.g. for logging to a file or using syslog isntead of console, you can check out the https://github.com/keycloak/keycloak/discussions/8870[Quarkus logging guide]. It is possible to use all properties mentioned there, as long as no other than the base logging dependency is involved. For example it is possible to set the log handler to file, but not to use json output, yet, as you would need to provide another dependency for json output to work.\n+\n+To use raw quarkus properties, please refer to the <@links.server id=\"configuration\"/> guide at section _Using unsupported server options_.\n+\n+</@tmpl.guide>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/resources/META-INF/services/quarkus.properties", "new_path": "quarkus/runtime/src/main/resources/META-INF/services/quarkus.properties", "diff": "# Default options that rely on Quarkus specific options and lacking proper support in Keycloak\n# Logging configuration. INFO is the default level for most of the categories\n+quarkus.log.min-level=TRACE\nquarkus.log.category.\"org.jboss.resteasy.resteasy_jaxrs.i18n\".level=WARN\nquarkus.log.category.\"org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup\".level=WARN\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/test/resources/META-INF/services/quarkus.properties", "new_path": "quarkus/runtime/src/test/resources/META-INF/services/quarkus.properties", "diff": "# Default options that rely on Quarkus specific options and lacking proper support in Keycloak\n# Logging configuration. INFO is the default level for most of the categories\n+quarkus.log.min-level=TRACE\nquarkus.log.level = INFO\nquarkus.log.category.\"org.jboss.resteasy.resteasy_jaxrs.i18n\".level=WARN\nquarkus.log.category.\"org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup\".level=WARN\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/servers/auth-server/quarkus/src/main/content/conf/quarkus.properties", "new_path": "testsuite/integration-arquillian/servers/auth-server/quarkus/src/main/content/conf/quarkus.properties", "diff": "+quarkus.log.min-level=TRACE\nquarkus.naming.enable-jndi=true\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Logging guide v1 Closes #10001
339,281
08.02.2022 13:59:45
-3,600
5701c6c85ae1000a266ba155bf9066010b4c7e35
JPA delegates can throw NoResultException when entity doesn't have any attributes Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/delegate/JpaClientDelegateProvider.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/delegate/JpaClientDelegateProvider.java", "diff": "@@ -57,7 +57,7 @@ public class JpaClientDelegateProvider extends JpaDelegateProvider<JpaClientEnti\nCriteriaBuilder cb = em.getCriteriaBuilder();\nCriteriaQuery<JpaClientEntity> query = cb.createQuery(JpaClientEntity.class);\nRoot<JpaClientEntity> root = query.from(JpaClientEntity.class);\n- root.fetch(\"attributes\", JoinType.INNER);\n+ root.fetch(\"attributes\", JoinType.LEFT);\nquery.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(getDelegate().getId())));\nsetDelegate(em.createQuery(query).getSingleResult());\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/delegate/JpaClientScopeDelegateProvider.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/delegate/JpaClientScopeDelegateProvider.java", "diff": "@@ -55,7 +55,7 @@ public class JpaClientScopeDelegateProvider extends JpaDelegateProvider<JpaClien\nCriteriaBuilder cb = em.getCriteriaBuilder();\nCriteriaQuery<JpaClientScopeEntity> query = cb.createQuery(JpaClientScopeEntity.class);\nRoot<JpaClientScopeEntity> root = query.from(JpaClientScopeEntity.class);\n- root.fetch(\"attributes\", JoinType.INNER);\n+ root.fetch(\"attributes\", JoinType.LEFT);\nquery.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(getDelegate().getId())));\nsetDelegate(em.createQuery(query).getSingleResult());\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/delegate/JpaRoleDelegateProvider.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/delegate/JpaRoleDelegateProvider.java", "diff": "@@ -55,7 +55,7 @@ public class JpaRoleDelegateProvider extends JpaDelegateProvider<JpaRoleEntity>\nCriteriaBuilder cb = em.getCriteriaBuilder();\nCriteriaQuery<JpaRoleEntity> query = cb.createQuery(JpaRoleEntity.class);\nRoot<JpaRoleEntity> root = query.from(JpaRoleEntity.class);\n- root.fetch(\"attributes\", JoinType.INNER);\n+ root.fetch(\"attributes\", JoinType.LEFT);\nquery.select(root).where(cb.equal(root.get(\"id\"), UUID.fromString(getDelegate().getId())));\nsetDelegate(em.createQuery(query).getSingleResult());\n" } ]
Java
Apache License 2.0
keycloak/keycloak
JPA delegates can throw NoResultException when entity doesn't have any attributes Closes #10067
339,618
08.02.2022 11:40:55
-3,600
c22299045c5fa78a149ec902b2e509ef01f77d92
remove profile references Closes
[ { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Environment.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Environment.java", "diff": "@@ -189,6 +189,36 @@ public final class Environment {\nSystem.setProperty(LAUNCH_MODE, \"test\");\n}\n+ /**\n+ * We want to hide the \"profiles\" from Quarkus to not make things unnecessarily complicated for users,\n+ * so this method returns the equivalent launch mode instead. For use in e.g. CLI Output.\n+ *\n+ * @param profile the internal profile string used\n+ * @return the mapped launch mode, none when nothing is given or the profile as is when its\n+ * neither null/empty nor matching the quarkus default profiles we use.\n+ */\n+ public static String getKeycloakModeFromProfile(String profile) {\n+\n+ if(profile == null || profile.isEmpty()) {\n+ return \"none\";\n+ }\n+\n+ if(profile.equals(LaunchMode.DEVELOPMENT.getDefaultProfile())) {\n+ return \"development\";\n+ }\n+\n+ if(profile.equals(LaunchMode.TEST.getDefaultProfile())) {\n+ return \"test\";\n+ }\n+\n+ if(profile.equals(LaunchMode.NORMAL.getDefaultProfile())) {\n+ return \"production\";\n+ }\n+\n+ //when no profile is matched and not empty, just return the profile name.\n+ return profile;\n+ }\n+\npublic static boolean isDistribution() {\nreturn getHomeDir() != null;\n}\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/KeycloakMain.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/KeycloakMain.java", "diff": "package org.keycloak.quarkus.runtime;\n+import static org.keycloak.quarkus.runtime.Environment.getKeycloakModeFromProfile;\nimport static org.keycloak.quarkus.runtime.Environment.isDevProfile;\nimport static org.keycloak.quarkus.runtime.Environment.getProfileOrDefault;\nimport static org.keycloak.quarkus.runtime.Environment.isTestLaunchMode;\n@@ -83,7 +84,7 @@ public class KeycloakMain implements QuarkusApplication {\nQuarkus.run(KeycloakMain.class, (exitCode, cause) -> {\nif (cause != null) {\nerrorHandler.error(errStream,\n- String.format(\"Failed to start server using profile (%s)\", getProfileOrDefault(\"prod\")),\n+ String.format(\"Failed to start server in (%s) mode\", getKeycloakModeFromProfile(getProfileOrDefault(\"prod\"))),\ncause.getCause());\n}\n@@ -95,7 +96,7 @@ public class KeycloakMain implements QuarkusApplication {\n});\n} catch (Throwable cause) {\nerrorHandler.error(errStream,\n- String.format(\"Unexpected error when starting the server using profile (%s)\", getProfileOrDefault(\"prod\")),\n+ String.format(\"Unexpected error when starting the server in (%s) mode\", getKeycloakModeFromProfile(getProfileOrDefault(\"prod\"))),\ncause.getCause());\n}\n}\n@@ -106,7 +107,7 @@ public class KeycloakMain implements QuarkusApplication {\n@Override\npublic int run(String... args) throws Exception {\nif (isDevProfile()) {\n- LOGGER.warnf(\"Running the server in dev mode. DO NOT use this configuration in production.\");\n+ LOGGER.warnf(\"Running the server in development mode. DO NOT use this configuration in production.\");\n}\nint exitCode = ApplicationLifecycleManager.getExitCode();\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Messages.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Messages.java", "diff": "@@ -52,7 +52,7 @@ public final class Messages {\n}\npublic static String devProfileNotAllowedError(String cmd) {\n- return String.format(\"You can not '%s' the server using the '%s' configuration profile. Please re-build the server first, using 'kc.sh build' for the default production profile, or using 'kc.sh build --profile=<profile>' with a profile more suitable for production.%n\", cmd, Environment.DEV_PROFILE_VALUE);\n+ return String.format(\"You can not '%s' the server in %s mode. Please re-build the server first, using 'kc.sh build' for the default production mode.%n\", cmd, Environment.getKeycloakModeFromProfile(Environment.DEV_PROFILE_VALUE));\n}\npublic static Throwable invalidLogLevel(String logLevel) {\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Build.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Build.java", "diff": "@@ -30,7 +30,6 @@ import io.quarkus.bootstrap.runner.RunnerClassLoader;\nimport io.quarkus.runtime.configuration.ProfileManager;\nimport picocli.CommandLine.Command;\n-import picocli.CommandLine.Mixin;\n@Command(name = Build.NAME,\nheader = \"Creates a new and optimized server image.\",\n@@ -46,9 +45,7 @@ import picocli.CommandLine.Mixin;\n\"Consider running this command before running the server in production for an optimal runtime.\"\n},\nfooterHeading = \"Examples:\",\n- footer = \" Optimize the server based on a profile configuration:%n%n\"\n- + \" $ ${PARENT-COMMAND-FULL-NAME:-$PARENTCOMMAND} --profile=prod ${COMMAND-NAME} %n%n\"\n- + \" Change the database vendor:%n%n\"\n+ footer = \" Change the database vendor:%n%n\"\n+ \" $ ${PARENT-COMMAND-FULL-NAME:-$PARENTCOMMAND} ${COMMAND-NAME} --db=postgres%n%n\"\n+ \" Enable a feature:%n%n\"\n+ \" $ ${PARENT-COMMAND-FULL-NAME:-$PARENTCOMMAND} ${COMMAND-NAME} --features=<feature_name>%n%n\"\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Main.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Main.java", "diff": "@@ -95,6 +95,7 @@ public final class Main {\n}\n@Option(names = { PROFILE_SHORT_NAME, PROFILE_LONG_NAME },\n+ hidden = true,\ndescription = \"Set the profile. Use 'dev' profile to enable development mode.\")\npublic void setProfile(String profile) {\nEnvironment.setProfile(profile);\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/ShowConfig.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/ShowConfig.java", "diff": "@@ -30,6 +30,7 @@ import java.util.function.Predicate;\nimport java.util.stream.Collectors;\nimport java.util.stream.StreamSupport;\n+import org.keycloak.quarkus.runtime.Environment;\nimport org.keycloak.quarkus.runtime.configuration.MicroProfileConfigProvider;\nimport org.keycloak.quarkus.runtime.configuration.PersistedConfigSource;\n@@ -76,7 +77,7 @@ public final class ShowConfig extends AbstractCommand implements Runnable {\nprivate void printRunTimeConfig(Map<String, Set<String>> properties, String profile) {\nSet<String> uniqueNames = new HashSet<>();\n- spec.commandLine().getOut().printf(\"Current Profile: %s%n\", profile == null ? \"none\" : profile);\n+ spec.commandLine().getOut().printf(\"Current Mode: %s%n\", Environment.getKeycloakModeFromProfile(profile));\nspec.commandLine().getOut().println(\"Runtime Configuration:\");\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/integration/QuarkusPlatform.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/integration/QuarkusPlatform.java", "diff": "@@ -150,7 +150,7 @@ public class QuarkusPlatform implements PlatformProvider {\nthis.tmpDir = tmpDir;\nlog.debugf(\"Using server tmp directory: %s\", tmpDir.getAbsolutePath());\n} else {\n- throw new RuntimeException(\"Temporary directory \" + tmpDir.getAbsolutePath() + \" does not exists and it was not possible to create it.\");\n+ throw new RuntimeException(\"Temporary directory \" + tmpDir.getAbsolutePath() + \" does not exist and it was not possible to create it.\");\n}\n}\nreturn tmpDir;\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/main/java/org/keycloak/it/junit5/extension/CLIResult.java", "new_path": "quarkus/tests/integration/src/main/java/org/keycloak/it/junit5/extension/CLIResult.java", "diff": "@@ -52,12 +52,12 @@ public interface CLIResult extends LaunchResult {\n}\ndefault void assertNotDevMode() {\n- assertFalse(getOutput().contains(\"Running the server in dev mode.\"),\n+ assertFalse(getOutput().contains(\"Running the server in development mode.\"),\n() -> \"The standard output:\\n\" + getOutput() + \"\\ndoes include the Start Dev output\");\n}\ndefault void assertStartedDevMode() {\n- assertTrue(getOutput().contains(\"Running the server in dev mode.\"),\n+ assertTrue(getOutput().contains(\"Running the server in development mode.\"),\n() -> \"The standard output:\\n\" + getOutput() + \"\\ndoesn't include the Start Dev output\");\n}\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/StartCommandTest.java", "new_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/StartCommandTest.java", "diff": "@@ -39,7 +39,7 @@ public class StartCommandTest {\n@Test\n@Launch({ \"--profile=dev\", \"start\" })\nvoid failUsingDevProfile(LaunchResult result) {\n- assertTrue(result.getErrorOutput().contains(\"ERROR: You can not 'start' the server using the 'dev' configuration profile. Please re-build the server first, using 'kc.sh build' for the default production profile, or using 'kc.sh build --profile=<profile>' with a profile more suitable for production.\"),\n+ assertTrue(result.getErrorOutput().contains(\"ERROR: You can not 'start' the server in development mode. Please re-build the server first, using 'kc.sh build' for the default production mode.\"),\n() -> \"The Output:\\n\" + result.getErrorOutput() + \"doesn't contains the expected string.\");\n}\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/BuildCommandDistTest.java", "new_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/BuildCommandDistTest.java", "diff": "@@ -48,7 +48,7 @@ class BuildCommandDistTest {\nvoid failIfDevProfile(LaunchResult result) {\nassertTrue(result.getErrorOutput().contains(\"ERROR: Failed to run 'build' command.\"),\n() -> \"The Error Output:\\n\" + result.getErrorOutput() + \"doesn't contains the expected string.\");\n- assertTrue(result.getErrorOutput().contains(\"ERROR: You can not 'build' the server using the 'dev' configuration profile. Please re-build the server first, using 'kc.sh build' for the default production profile, or using 'kc.sh build --profile=<profile>' with a profile more suitable for production.\"),\n+ assertTrue(result.getErrorOutput().contains(\"You can not 'build' the server in development mode. Please re-build the server first, using 'kc.sh build' for the default production mode.\"),\n() -> \"The Error Output:\\n\" + result.getErrorOutput() + \"doesn't contains the expected string.\");\nassertTrue(result.getErrorOutput().contains(\"For more details run the same command passing the '--verbose' option. Also you can use '--help' to see the details about the usage of the particular command.\"),\n() -> \"The Error Output:\\n\" + result.getErrorOutput() + \"doesn't contains the expected string.\");\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/StartCommandDistTest.java", "new_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/StartCommandDistTest.java", "diff": "@@ -35,7 +35,7 @@ public class StartCommandDistTest extends StartCommandTest {\n@Test\n@Launch({ \"-pf=dev\", \"start\", \"--auto-build\", \"--http-enabled=true\", \"--hostname-strict=false\" })\nvoid failIfAutoBuildUsingDevProfile(LaunchResult result) {\n- assertTrue(result.getErrorOutput().contains(\"ERROR: You can not 'start' the server using the 'dev' configuration profile. Please re-build the server first, using 'kc.sh build' for the default production profile, or using 'kc.sh build --profile=<profile>' with a profile more suitable for production.\"),\n+ assertTrue(result.getErrorOutput().contains(\"You can not 'start' the server in development mode. Please re-build the server first, using 'kc.sh build' for the default production mode.\"),\n() -> \"The Output:\\n\" + result.getErrorOutput() + \"doesn't contains the expected string.\");\nassertEquals(4, result.getErrorStream().size());\n}\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt", "new_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt", "diff": "Binary files a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt and b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt differ\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testDefaultToHelp.approved.txt", "new_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testDefaultToHelp.approved.txt", "diff": "Binary files a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testDefaultToHelp.approved.txt and b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testDefaultToHelp.approved.txt differ\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelp.approved.txt", "new_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelp.approved.txt", "diff": "Binary files a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelp.approved.txt and b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelp.approved.txt differ\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelpShort.approved.txt", "new_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelpShort.approved.txt", "diff": "Binary files a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelpShort.approved.txt and b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testHelpShort.approved.txt differ\n" } ]
Java
Apache License 2.0
keycloak/keycloak
remove profile references Closes #9683
339,284
09.02.2022 22:32:13
-32,400
c54920fd0e8156dd31161809388a8241af9ccdf1
fix(themes/keycloak.v2): mixed tags in index.ftl SVG spinner missed its closing tag spinner wrapper opened 1 div but closed 3
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak.v2/account/index.ftl", "new_path": "themes/src/main/resources/theme/keycloak.v2/account/index.ftl", "diff": "<path d=\"M10 50A40 40 0 0 0 90 50A40 42 0 0 1 10 50\" fill=\"#5DBCD2\" stroke=\"none\" transform=\"rotate(16.3145 50 51)\">\n<animateTransform attributeName=\"transform\" type=\"rotate\" dur=\"1s\" repeatCount=\"indefinite\" keyTimes=\"0;1\" values=\"0 50 51;360 50 51\"></animateTransform>\n</path>\n- </div>\n- </div>\n+ </svg>\n</div>\n</div>\n</div>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
fix(themes/keycloak.v2): mixed tags in index.ftl (#9884) - SVG spinner missed its closing tag - spinner wrapper opened 1 div but closed 3
339,618
09.02.2022 14:39:53
-3,600
f78b8bf89ff3f6a4fbb057e3cb92342a199ff8af
Add note about escaping in CLI Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/configuration.adoc", "new_path": "docs/guides/src/main/server/configuration.adoc", "diff": "@@ -97,6 +97,8 @@ The second stage involves starting the server using any **configuration option**\nAt this stage, you are free to set any value you want to any of the configuration options.\n+Be aware that you need to escape characters when invoking commands containing special shell characters such as `;` using the CLI, so you might want to set it in the configuration file instead.\n+\n== Configuring the server for an optimal startup time\nIn addition to the optimizations performed when you run the `build` command, you might want to avoid using CLI options when running the\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/db.adoc", "new_path": "docs/guides/src/main/server/db.adoc", "diff": "@@ -55,6 +55,7 @@ The server uses JDBC as the underlying technology to communicate with the relati\n.Starting the server\n<@kc.start parameters=\"--db-url jdbc:postgresql://mypostgres/mydatabase\"/>\n+Be aware that you need to escape characters when invoking commands containing special shell characters such as `;` using the CLI, so you might want to set it in the configuration file instead.\n== Configuring the database for Unicode\n" }, { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/logging.adoc", "new_path": "docs/guides/src/main/server/logging.adoc", "diff": "@@ -80,7 +80,7 @@ The format string supports the following symbols:\n=== Set the logging format\nTo set the logging format for a logged line, build your desired format template using the table above and run the following command:\n<@kc.start parameters=\"--log-format=\\\"\\'<format>\\'\\\"\"/>\n-Be aware that you need to escape characters when invoking the command using the CLI, so you might want to set it in the configuration file instead.\n+Be aware that you need to escape characters when invoking commands containing special shell characters such as `;` using the CLI, so you might want to set it in the configuration file instead.\n.Example: Abbreviate the fully qualified category name\n<@kc.start parameters=\"\\\"\\'%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c{3.}] (%t) %s%e%n\\'\\\"\"/>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add note about escaping in CLI (#10083) Closes #9999
339,410
07.02.2022 14:11:50
-3,600
de7be3d65d8e43efec05031075ba569e23c60d78
Handling JPA Map storage case when parent has been deleted Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaOptimisticLockingListener.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaOptimisticLockingListener.java", "diff": "@@ -28,6 +28,7 @@ import org.hibernate.event.spi.PreUpdateEventListener;\nimport org.keycloak.models.map.storage.jpa.JpaChildEntity;\nimport javax.persistence.LockModeType;\n+import java.util.Objects;\n/**\n* Listen on changes on child entities and forces an optimistic locking increment on the topmost parent aka root.\n@@ -46,10 +47,17 @@ public class JpaOptimisticLockingListener implements PreInsertEventListener, Pre\nObject root = entity;\nwhile (root instanceof JpaChildEntity) {\nroot = ((JpaChildEntity<?>) entity).getParent();\n+ Objects.requireNonNull(root, \"children must always return their parent, never null\");\n}\n+\n+ // a session would not contain the entity if it has been deleted\n+ // if the entity has been deleted JPA would throw an IllegalArgumentException with the message\n+ // \"entity not in the persistence context\".\n+ if (session.contains(root)) {\nsession.lock(root, LockModeType.OPTIMISTIC_FORCE_INCREMENT);\n}\n}\n+ }\n@Override\npublic boolean onPreInsert(PreInsertEvent event) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Handling JPA Map storage case when parent has been deleted Closes #10033
339,618
09.02.2022 14:58:31
-3,600
d8097ee7a5027720893040cf4877df3c1727279b
Add paragraph about mTLS configuration Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/enabletls.adoc", "new_path": "docs/guides/src/main/server/enabletls.adoc", "diff": "<#import \"/templates/guide.adoc\" as tmpl>\n<#import \"/templates/kc.adoc\" as kc>\n+<#import \"/templates/links.adoc\" as links>\n<@tmpl.guide\ntitle=\"Configuring TLS\"\n@@ -63,5 +64,13 @@ If no password is set, the default password `password` is used.\nAvoid setting a password in plaintext by using the CLI or adding it to `conf/keycloak.conf` file.\nInstead use good practices such as using a vault / mounted secret. For more detail, see the Vault Guide / Production deployment guide.\n+== Enabling mutual TLS\n+Authentication using mTLS is disabled by default. To enable mTLS certificate handling when Keycloak is the server and needs to validate certificates from requests made to Keycloaks endpoints, put the appropriate certificates in Keycloaks truststore and use the following command to enable mTLS:\n+\n+<@kc.start parameters=\"--https-client-auth=<none|request|required>\"/>\n+\n+Using the value `required` sets up Keycloak to always ask for certificates and fail if no certificate is provided in a request. By setting the value to `request`, Keycloak will also accept requests without a certificate and only validate the correctness of a certificate if it exists.\n+\n+Be aware that this is the basic certificate configuration for mTLS use cases where Keycloak acts as server. When Keycloak acts as client instead, e.g. when Keycloak tries to get a token from a token endpoint of a brokered identity provider that is secured by mTLS, you need to set up the HttpClient to provide the right certificates in the keystore for the outgoing request. To configure mTLS in these scenarios, see the <@links.server id=\"outgoinghttp\"/> guide.\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add paragraph about mTLS configuration (#10084) Closes #10041
339,618
10.02.2022 06:51:53
-3,600
23e5bc7aa3993b3ff7526549cd2389ee7e5877e7
Readme review v1
[ { "change_type": "MODIFY", "old_path": "quarkus/dist/src/main/README.md", "new_path": "quarkus/dist/src/main/README.md", "diff": "-Keycloak.X\n-==========\n+Keycloak\n+========\nTo get help configuring Keycloak via the CLI, run:\n@@ -23,4 +23,4 @@ on Windows:\nAfter the server boots, open http://localhost:8080 in your web browser. The welcome page will indicate that the server is running.\n-To get started, check the [Server Administration Guide](https://www.keycloak.org/docs/latest/server_admin).\n\\ No newline at end of file\n+To get started, check out the [configuration guides](https://www.keycloak.org/guides#server).\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "quarkus/dist/src/main/content/conf/README.md", "new_path": "quarkus/dist/src/main/content/conf/README.md", "diff": "Configure the server\n====================\n-Use files in this directory to configure the server.\n\\ No newline at end of file\n+Files in this directory are used to configure the server. Please consult the [configuration guides](https://www.keycloak.org/guides#server) for more information.\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "quarkus/dist/src/main/content/themes/README.md", "new_path": "quarkus/dist/src/main/content/themes/README.md", "diff": "@@ -3,13 +3,13 @@ Creating Themes\nThemes are used to configure the look and feel of login pages and the account management console.\n-Custom themes packaged in a JAR file should be deployed to the `${kc.home.dir}/providers` directory and you should run\n-the `build` command to install them prior to running the server.\n+Custom themes packaged in a JAR file should be deployed to the `${kc.home.dir}/providers` directory. After that, run\n+the `build` command to install them before starting the server.\nYou are also able to create your custom themes in this directory, directly. Themes within this directory do not require\n-the `build` command to install them.\n+the `build` command to be installed.\n-When running the server in development mode, themes are not cached so that you can easily work on them without any need to restart\n+When running the server in development mode using `start-dev`, themes are not cached so that you can easily work on them without a need to restart\nthe server when making changes.\nSee the theme section in the [Server Developer Guide](https://www.keycloak.org/docs/latest/server_development/#_themes) for more details about how to create custom themes.\n@@ -17,7 +17,7 @@ See the theme section in the [Server Developer Guide](https://www.keycloak.org/d\nOverriding the built-in templates\n---------------------------------\n-While creating custom themes especially when overriding templates it may be useful to use the built-in templates as\n+While creating custom themes, especially when overriding templates, it may be useful to use the built-in templates as\na reference. These can be found within the theme directory of `../lib/lib/main/org.keycloak.keycloak-themes-${project.version}.jar`, which can be opened using any\nstandard ZIP archive tool.\n" }, { "change_type": "MODIFY", "old_path": "quarkus/dist/src/main/version.txt", "new_path": "quarkus/dist/src/main/version.txt", "diff": "-Keycloak.X - Version ${product.version}\n+Keycloak - Version ${product.version}\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/MariaDBStartDatabaseTest.java", "new_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/MariaDBStartDatabaseTest.java", "diff": "package org.keycloak.it.storage.database;\n-import org.junit.jupiter.api.Test;\nimport org.keycloak.it.junit5.extension.CLIResult;\nimport org.keycloak.it.junit5.extension.CLITest;\nimport org.keycloak.it.junit5.extension.WithDatabase;\n-import io.quarkus.test.junit.main.Launch;\n-import io.quarkus.test.junit.main.LaunchResult;\n-\n@CLITest\n@WithDatabase(alias = \"mariadb\")\npublic class MariaDBStartDatabaseTest extends AbstractStartDabataseTest {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Readme review v1 (#10082)
339,269
10.02.2022 08:01:51
-3,600
011d108fff1554e1784e0b9c70552e45ded7ec50
10073 reduced quarkus image size
[ { "change_type": "MODIFY", "old_path": "quarkus/container/Dockerfile", "new_path": "quarkus/container/Dockerfile", "diff": "@@ -15,16 +15,16 @@ RUN (cd /tmp/keycloak && \\\nRUN mv /tmp/keycloak/keycloak-* /opt/keycloak\n+RUN chmod -R g+rwX /opt/keycloak\n+\nFROM registry.access.redhat.com/ubi8-minimal\n-COPY --from=build-env /opt/keycloak /opt/keycloak\n+COPY --from=build-env --chown=1000:0 /opt/keycloak /opt/keycloak\nRUN microdnf update -y && \\\nmicrodnf install -y java-11-openjdk-headless && microdnf clean all && rm -rf /var/cache/yum/* && \\\necho \"keycloak:x:0:root\" >> /etc/group && \\\n- echo \"keycloak:x:1000:0:keycloak user:/opt/keycloak:/sbin/nologin\" >> /etc/passwd && \\\n- chown -R keycloak:root /opt/keycloak && \\\n- chmod -R g+rwX /opt/keycloak\n+ echo \"keycloak:x:1000:0:keycloak user:/opt/keycloak:/sbin/nologin\" >> /etc/passwd\nUSER 1000\n" } ]
Java
Apache License 2.0
keycloak/keycloak
10073 reduced quarkus image size (#10074)
339,281
10.02.2022 15:14:58
-3,600
8a8d59a1249d4c4930458cbe5627f8e1c2f3756a
Add prefix "kc_" to all existing tables Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientAttributeEntity.java", "diff": "@@ -21,7 +21,7 @@ import javax.persistence.Table;\nimport org.keycloak.models.map.storage.jpa.JpaAttributeEntity;\n@Entity\n-@Table(name = \"client_attribute\")\n+@Table(name = \"kc_client_attribute\")\npublic class JpaClientAttributeEntity extends JpaAttributeEntity<JpaClientEntity> {\npublic JpaClientAttributeEntity() {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/client/entity/JpaClientEntity.java", "diff": "@@ -53,7 +53,7 @@ import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n* therefore marked as non-insertable and non-updatable to instruct hibernate.\n*/\n@Entity\n-@Table(name = \"client\",\n+@Table(name = \"kc_client\",\nuniqueConstraints = {\n@UniqueConstraint(\ncolumnNames = {\"realmId\", \"clientId\"}\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeAttributeEntity.java", "diff": "@@ -21,7 +21,7 @@ import javax.persistence.Table;\nimport org.keycloak.models.map.storage.jpa.JpaAttributeEntity;\n@Entity\n-@Table(name = \"client_scope_attribute\")\n+@Table(name = \"kc_client_scope_attribute\")\npublic class JpaClientScopeAttributeEntity extends JpaAttributeEntity<JpaClientScopeEntity> {\npublic JpaClientScopeAttributeEntity() {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/clientscope/entity/JpaClientScopeEntity.java", "diff": "@@ -53,7 +53,7 @@ import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n* therefore marked as non-insertable and non-updatable to instruct hibernate.\n*/\n@Entity\n-@Table(name = \"client_scope\", uniqueConstraints = {@UniqueConstraint(columnNames = {\"realmId\", \"name\"})})\n+@Table(name = \"kc_client_scope\", uniqueConstraints = {@UniqueConstraint(columnNames = {\"realmId\", \"name\"})})\n@TypeDefs({@TypeDef(name = \"jsonb\", typeClass = JsonbType.class)})\npublic class JpaClientScopeEntity extends AbstractClientScopeEntity implements JpaRootEntity {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleAttributeEntity.java", "diff": "@@ -21,7 +21,7 @@ import javax.persistence.Table;\nimport org.keycloak.models.map.storage.jpa.JpaAttributeEntity;\n@Entity\n-@Table(name = \"role_attribute\")\n+@Table(name = \"kc_role_attribute\")\npublic class JpaRoleAttributeEntity extends JpaAttributeEntity<JpaRoleEntity> {\npublic JpaRoleAttributeEntity() {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/role/entity/JpaRoleEntity.java", "diff": "@@ -51,7 +51,7 @@ import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;\n* therefore marked as non-insertable and non-updatable to instruct hibernate.\n*/\n@Entity\n-@Table(name = \"role\", uniqueConstraints = {@UniqueConstraint(columnNames = {\"realmId\", \"clientId\", \"name\"})})\n+@Table(name = \"kc_role\", uniqueConstraints = {@UniqueConstraint(columnNames = {\"realmId\", \"clientId\", \"name\"})})\n@TypeDefs({@TypeDef(name = \"jsonb\", typeClass = JsonbType.class)})\npublic class JpaRoleEntity extends AbstractRoleEntity implements JpaRootEntity {\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/client-scopes/jpa-client-scopes-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/client-scopes/jpa-client-scopes-changelog-1.xml", "diff": "@@ -25,7 +25,7 @@ limitations under the License.\n<!-- format of id of changeSet: client-scopes-${org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_CLIENT_SCOPE} -->\n<changeSet author=\"keycloak\" id=\"client-scopes-1\">\n- <createTable tableName=\"client_scope\">\n+ <createTable tableName=\"kc_client_scope\">\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n@@ -34,33 +34,33 @@ limitations under the License.\n</column>\n<column name=\"metadata\" type=\"json\"/>\n</createTable>\n- <ext:addGeneratedColumn tableName=\"client_scope\">\n+ <ext:addGeneratedColumn tableName=\"kc_client_scope\">\n<ext:column name=\"entityversion\" type=\"INTEGER\" jsonColumn=\"metadata\" jsonProperty=\"entityVersion\"/>\n<ext:column name=\"realmid\" type=\"VARCHAR(36)\" jsonColumn=\"metadata\" jsonProperty=\"fRealmId\"/>\n<ext:column name=\"name\" type=\"VARCHAR(255)\" jsonColumn=\"metadata\" jsonProperty=\"fName\"/>\n</ext:addGeneratedColumn>\n- <createIndex tableName=\"client_scope\" indexName=\"client_scope_entityVersion\">\n+ <createIndex tableName=\"kc_client_scope\" indexName=\"client_scope_entityVersion\">\n<column name=\"entityversion\"/>\n</createIndex>\n- <createIndex tableName=\"client_scope\" indexName=\"client_realmId_name\" unique=\"true\">\n+ <createIndex tableName=\"kc_client_scope\" indexName=\"client_realmId_name\" unique=\"true\">\n<column name=\"realmid\"/>\n<column name=\"name\"/>\n</createIndex>\n- <createTable tableName=\"client_scope_attribute\">\n+ <createTable tableName=\"kc_client_scope_attribute\">\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n<column name=\"fk_root\" type=\"UUID\">\n- <constraints foreignKeyName=\"client_scope_attr_fk_root_fkey\" references=\"client_scope(id)\" deleteCascade=\"true\"/>\n+ <constraints foreignKeyName=\"client_scope_attr_fk_root_fkey\" references=\"kc_client_scope(id)\" deleteCascade=\"true\"/>\n</column>\n<column name=\"name\" type=\"VARCHAR(255)\"/>\n<column name=\"value\" type=\"text\"/>\n</createTable>\n- <createIndex tableName=\"client_scope_attribute\" indexName=\"client_scope_attr_fk_root\">\n+ <createIndex tableName=\"kc_client_scope_attribute\" indexName=\"client_scope_attr_fk_root\">\n<column name=\"fk_root\"/>\n</createIndex>\n- <createIndex tableName=\"client_scope_attribute\" indexName=\"client_scope_attr_name_value\">\n+ <createIndex tableName=\"kc_client_scope_attribute\" indexName=\"client_scope_attr_name_value\">\n<column name=\"name\"/>\n<column name=\"VALUE(255)\" valueComputed=\"VALUE(255)\"/>\n</createIndex>\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "diff": "@@ -25,7 +25,7 @@ limitations under the License.\n<!-- format of id of changeSet: clients-${org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_CLIENT} -->\n<changeSet author=\"keycloak\" id=\"clients-1\">\n- <createTable tableName=\"client\">\n+ <createTable tableName=\"kc_client\">\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n@@ -34,17 +34,17 @@ limitations under the License.\n</column>\n<column name=\"metadata\" type=\"json\"/>\n</createTable>\n- <ext:addGeneratedColumn tableName=\"client\">\n+ <ext:addGeneratedColumn tableName=\"kc_client\">\n<ext:column name=\"entityversion\" type=\"INTEGER\" jsonColumn=\"metadata\" jsonProperty=\"entityVersion\"/>\n<ext:column name=\"realmid\" type=\"VARCHAR(36)\" jsonColumn=\"metadata\" jsonProperty=\"fRealmId\"/>\n<ext:column name=\"clientid\" type=\"VARCHAR(255)\" jsonColumn=\"metadata\" jsonProperty=\"fClientId\"/>\n<ext:column name=\"protocol\" type=\"VARCHAR(36)\" jsonColumn=\"metadata\" jsonProperty=\"fProtocol\"/>\n<ext:column name=\"enabled\" type=\"BOOLEAN\" jsonColumn=\"metadata\" jsonProperty=\"fEnabled\"/>\n</ext:addGeneratedColumn>\n- <createIndex tableName=\"client\" indexName=\"client_entityVersion\">\n+ <createIndex tableName=\"kc_client\" indexName=\"client_entityVersion\">\n<column name=\"entityversion\"/>\n</createIndex>\n- <createIndex tableName=\"client\" indexName=\"client_realmId_clientId\" unique=\"true\">\n+ <createIndex tableName=\"kc_client\" indexName=\"client_realmId_clientId\" unique=\"true\">\n<column name=\"realmid\"/>\n<column name=\"clientid\"/>\n</createIndex>\n@@ -54,20 +54,20 @@ limitations under the License.\n</ext:createJsonIndex>\n-->\n- <createTable tableName=\"client_attribute\">\n+ <createTable tableName=\"kc_client_attribute\">\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n<column name=\"fk_root\" type=\"UUID\">\n- <constraints foreignKeyName=\"client_attr_fk_root_fkey\" references=\"client(id)\" deleteCascade=\"true\"/>\n+ <constraints foreignKeyName=\"client_attr_fk_root_fkey\" references=\"kc_client(id)\" deleteCascade=\"true\"/>\n</column>\n<column name=\"name\" type=\"VARCHAR(255)\"/>\n<column name=\"value\" type=\"text\"/>\n</createTable>\n- <createIndex tableName=\"client_attribute\" indexName=\"client_attr_fk_root\">\n+ <createIndex tableName=\"kc_client_attribute\" indexName=\"client_attr_fk_root\">\n<column name=\"fk_root\"/>\n</createIndex>\n- <createIndex tableName=\"client_attribute\" indexName=\"client_attr_name_value\">\n+ <createIndex tableName=\"kc_client_attribute\" indexName=\"client_attr_name_value\">\n<column name=\"name\"/>\n<column name=\"VALUE(255)\" valueComputed=\"VALUE(255)\"/>\n</createIndex>\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/roles/jpa-roles-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/roles/jpa-roles-changelog-1.xml", "diff": "@@ -25,7 +25,7 @@ limitations under the License.\n<!-- format of id of changeSet: roles-${org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_ROLE} -->\n<changeSet author=\"keycloak\" id=\"roles-1\">\n- <createTable tableName=\"role\">\n+ <createTable tableName=\"kc_role\">\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n@@ -34,17 +34,17 @@ limitations under the License.\n</column>\n<column name=\"metadata\" type=\"json\"/>\n</createTable>\n- <ext:addGeneratedColumn tableName=\"role\">\n+ <ext:addGeneratedColumn tableName=\"kc_role\">\n<ext:column name=\"entityversion\" type=\"INTEGER\" jsonColumn=\"metadata\" jsonProperty=\"entityVersion\"/>\n<ext:column name=\"realmid\" type=\"VARCHAR(255)\" jsonColumn=\"metadata\" jsonProperty=\"fRealmId\"/>\n<ext:column name=\"name\" type=\"VARCHAR(36)\" jsonColumn=\"metadata\" jsonProperty=\"fName\"/>\n<ext:column name=\"clientid\" type=\"VARCHAR(255)\" jsonColumn=\"metadata\" jsonProperty=\"fClientId\"/>\n<ext:column name=\"description\" type=\"VARCHAR(255)\" jsonColumn=\"metadata\" jsonProperty=\"fDescription\"/>\n</ext:addGeneratedColumn>\n- <createIndex tableName=\"role\" indexName=\"role_entityVersion\">\n+ <createIndex tableName=\"kc_role\" indexName=\"role_entityVersion\">\n<column name=\"entityversion\"/>\n</createIndex>\n- <createIndex tableName=\"role\" indexName=\"role_realmId_clientid_name\" unique=\"true\">\n+ <createIndex tableName=\"kc_role\" indexName=\"role_realmId_clientid_name\" unique=\"true\">\n<column name=\"realmid\"/>\n<column name=\"clientid\"/>\n<column name=\"name\"/>\n@@ -56,20 +56,20 @@ limitations under the License.\n</ext:createJsonIndex>\n-->\n- <createTable tableName=\"role_attribute\">\n+ <createTable tableName=\"kc_role_attribute\">\n<column name=\"id\" type=\"UUID\">\n<constraints primaryKey=\"true\" nullable=\"false\"/>\n</column>\n<column name=\"fk_root\" type=\"UUID\">\n- <constraints foreignKeyName=\"role_attr_fk_root_fkey\" references=\"role(id)\" deleteCascade=\"true\"/>\n+ <constraints foreignKeyName=\"role_attr_fk_root_fkey\" references=\"kc_role(id)\" deleteCascade=\"true\"/>\n</column>\n<column name=\"name\" type=\"VARCHAR(255)\"/>\n<column name=\"value\" type=\"text\"/>\n</createTable>\n- <createIndex tableName=\"role_attribute\" indexName=\"role_attr_fk_root\">\n+ <createIndex tableName=\"kc_role_attribute\" indexName=\"role_attr_fk_root\">\n<column name=\"fk_root\"/>\n</createIndex>\n- <createIndex tableName=\"role_attribute\" indexName=\"role_attr_name_value\">\n+ <createIndex tableName=\"kc_role_attribute\" indexName=\"role_attr_name_value\">\n<column name=\"name\"/>\n<column name=\"VALUE(255)\" valueComputed=\"VALUE(255)\"/>\n</createIndex>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add prefix "kc_" to all existing tables Closes #10101
339,546
09.02.2022 11:30:16
-3,600
f54cd969f8c22557e56df3782aad5b8ad77e49c6
OTPPolicyTest failures resolve Tests pass locally, Closes
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/console/src/main/java/org/keycloak/testsuite/console/page/authentication/otppolicy/OTPPolicyForm.java", "new_path": "testsuite/integration-arquillian/tests/other/console/src/main/java/org/keycloak/testsuite/console/page/authentication/otppolicy/OTPPolicyForm.java", "diff": "@@ -45,24 +45,27 @@ public class OTPPolicyForm extends Form {\n@FindBy(id = \"lookAhead\")\nprivate WebElement lookAhead;\n+ @FindBy(id = \"lookAround\")\n+ private WebElement lookAround;\n+\n@FindBy(id = \"period\")\nprivate WebElement period;\n@FindBy(id = \"counter\")\nprivate WebElement counter;\n- public void setValues(OTPType otpType, OTPHashAlg otpHashAlg, Digits digits, String lookAhead, String periodOrCounter) {\n+ public void setValues(OTPType otpType, OTPHashAlg otpHashAlg, Digits digits, String lookAheadOrAround, String periodOrCounter) {\nthis.otpType.selectByValue(otpType.getName());\nthis.otpHashAlg.selectByValue(otpHashAlg.getName());\nthis.digits.selectByVisibleText(\"\" + digits.getName());\n- UIUtils.setTextInputValue(this.lookAhead, lookAhead);\n-\nswitch (otpType) {\ncase TIME_BASED:\n+ UIUtils.setTextInputValue(this.lookAround, lookAheadOrAround);\nUIUtils.setTextInputValue(period, periodOrCounter);\nbreak;\ncase COUNTER_BASED:\n+ UIUtils.setTextInputValue(this.lookAhead, lookAheadOrAround);\nUIUtils.setTextInputValue(counter, periodOrCounter);\nbreak;\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/authentication/OTPPolicyTest.java", "new_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/authentication/OTPPolicyTest.java", "diff": "@@ -65,6 +65,7 @@ public class OTPPolicyTest extends AbstractConsoleTest {\nassertAlertSuccess();\nrealm = testRealmResource().toRepresentation();\n+ assertEquals(\"totp\", realm.getOtpPolicyType());\nassertEquals(Integer.valueOf(40), realm.getOtpPolicyPeriod());\n}\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/otp-policy.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/otp-policy.html", "diff": "</div>\n<div class=\"form-group\" data-ng-if=\"realm.otpPolicyType == 'totp'\">\n- <label class=\"col-md-2 control-label\" for=\"lookAhead\">{{:: 'look-around-window' | translate}}</label>\n+ <label class=\"col-md-2 control-label\" for=\"lookAround\">{{:: 'look-around-window' | translate}}</label>\n<div class=\"col-md-6\">\n<input class=\"form-control\" type=\"number\" data-ng-required=\"realm.otpPolicyType == 'totp'\" min=\"0\" max=\"120\" id=\"lookAround\" name=\"lookAround\" data-ng-model=\"realm.otpPolicyLookAheadWindow\">\n</div>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
OTPPolicyTest failures resolve Tests pass locally, Closes #9692
339,500
09.02.2022 14:28:06
-3,600
26ac142b999af88c4c969ea95032c59e49cc4e96
Hot Rod map storage: Roles no-downtime store
[ { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/HotRodMapStorageProviderFactory.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/HotRodMapStorageProviderFactory.java", "diff": "@@ -25,8 +25,12 @@ import org.keycloak.models.ClientModel;\nimport org.keycloak.models.GroupModel;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.KeycloakSessionFactory;\n+import org.keycloak.models.RoleModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.map.group.MapGroupEntity;\n+import org.keycloak.models.map.role.MapRoleEntity;\n+import org.keycloak.models.map.storage.hotRod.role.HotRodRoleEntity;\n+import org.keycloak.models.map.storage.hotRod.role.HotRodRoleEntityDelegate;\nimport org.keycloak.models.map.storage.hotRod.client.HotRodClientEntity;\nimport org.keycloak.models.map.storage.hotRod.client.HotRodClientEntityDelegate;\nimport org.keycloak.models.map.storage.hotRod.client.HotRodProtocolMapperEntityDelegate;\n@@ -62,6 +66,7 @@ public class HotRodMapStorageProviderFactory implements AmphibianProviderFactory\n.constructor(MapClientEntity.class, HotRodClientEntityDelegate::new)\n.constructor(MapProtocolMapperEntity.class, HotRodProtocolMapperEntityDelegate::new)\n.constructor(MapGroupEntity.class, HotRodGroupEntityDelegate::new)\n+ .constructor(MapRoleEntity.class, HotRodRoleEntityDelegate::new)\n.constructor(MapUserEntity.class, HotRodUserEntityDelegate::new)\n.constructor(MapUserCredentialEntity.class, HotRodUserCredentialEntityDelegate::new)\n.constructor(MapUserFederatedIdentityEntity.class, HotRodUserFederatedIdentityEntityDelegate::new)\n@@ -81,6 +86,13 @@ public class HotRodMapStorageProviderFactory implements AmphibianProviderFactory\nnew HotRodEntityDescriptor<>(GroupModel.class,\nHotRodGroupEntity.class,\nHotRodGroupEntityDelegate::new));\n+\n+ // Roles descriptor\n+ ENTITY_DESCRIPTOR_MAP.put(RoleModel.class,\n+ new HotRodEntityDescriptor<>(RoleModel.class,\n+ HotRodRoleEntity.class,\n+ HotRodRoleEntityDelegate::new));\n+\n// Users descriptor\nENTITY_DESCRIPTOR_MAP.put(UserModel.class,\nnew HotRodEntityDescriptor<>(UserModel.class,\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/IckleQueryMapModelCriteriaBuilder.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/IckleQueryMapModelCriteriaBuilder.java", "diff": "@@ -59,6 +59,8 @@ public class IckleQueryMapModelCriteriaBuilder<E extends AbstractHotRodEntity, M\nINFINISPAN_NAME_OVERRIDES.put(GroupModel.SearchableFields.PARENT_ID, \"parentId\");\nINFINISPAN_NAME_OVERRIDES.put(GroupModel.SearchableFields.ASSIGNED_ROLE, \"grantedRoles\");\n+ INFINISPAN_NAME_OVERRIDES.put(RoleModel.SearchableFields.IS_CLIENT_ROLE, \"clientRole\");\n+\nINFINISPAN_NAME_OVERRIDES.put(UserModel.SearchableFields.SERVICE_ACCOUNT_CLIENT, \"serviceAccountClientLink\");\nINFINISPAN_NAME_OVERRIDES.put(UserModel.SearchableFields.CONSENT_FOR_CLIENT, \"userConsents.clientId\");\nINFINISPAN_NAME_OVERRIDES.put(UserModel.SearchableFields.CONSENT_WITH_CLIENT_SCOPE, \"userConsents.grantedClientScopesIds\");\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/HotRodUtils.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/HotRodUtils.java", "diff": "@@ -41,6 +41,9 @@ import java.util.Set;\n* @author <a href=\"mailto:[email protected]\">Martin Kanis</a>\n*/\npublic class HotRodUtils {\n+\n+ public static final int DEFAULT_MAX_RESULTS = Integer.MAX_VALUE >> 1;\n+\n/**\n* Not suitable for a production usage. Only for development and test purposes.\n* Also do not use in clustered environment.\n@@ -89,6 +92,11 @@ public class HotRodUtils {\npublic static <T> Query<T> paginateQuery(Query<T> query, Integer first, Integer max) {\nif (first != null && first > 0) {\nquery = query.startOffset(first);\n+\n+ // workaround because of ISPN-13702 bug, see https://github.com/keycloak/keycloak/issues/10090\n+ if (max == null || max < 0) {\n+ max = DEFAULT_MAX_RESULTS;\n+ }\n}\nif (max != null && max >= 0) {\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/ProtoSchemaInitializer.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/ProtoSchemaInitializer.java", "diff": "@@ -22,6 +22,7 @@ import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;\nimport org.keycloak.models.map.storage.hotRod.client.HotRodClientEntity;\nimport org.keycloak.models.map.storage.hotRod.client.HotRodProtocolMapperEntity;\nimport org.keycloak.models.map.storage.hotRod.group.HotRodGroupEntity;\n+import org.keycloak.models.map.storage.hotRod.role.HotRodRoleEntity;\nimport org.keycloak.models.map.storage.hotRod.user.HotRodUserConsentEntity;\nimport org.keycloak.models.map.storage.hotRod.user.HotRodUserCredentialEntity;\nimport org.keycloak.models.map.storage.hotRod.user.HotRodUserEntity;\n@@ -39,6 +40,9 @@ import org.keycloak.models.map.storage.hotRod.user.HotRodUserFederatedIdentityEn\n// Groups\nHotRodGroupEntity.class,\n+ // Roles\n+ HotRodRoleEntity.class,\n+\n// Users\nHotRodUserEntity.class,\nHotRodUserConsentEntity.class,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/role/HotRodRoleEntity.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.keycloak.models.map.storage.hotRod.role;\n+\n+import org.infinispan.protostream.annotations.ProtoDoc;\n+import org.infinispan.protostream.annotations.ProtoField;\n+import org.keycloak.models.map.annotations.GenerateHotRodEntityImplementation;\n+import org.keycloak.models.map.role.MapRoleEntity;\n+import org.keycloak.models.map.storage.hotRod.common.AbstractHotRodEntity;\n+import org.keycloak.models.map.storage.hotRod.common.HotRodAttributeEntityNonIndexed;\n+import org.keycloak.models.map.storage.hotRod.common.UpdatableHotRodEntityDelegateImpl;\n+\n+import java.util.Objects;\n+import java.util.Set;\n+\n+@GenerateHotRodEntityImplementation(\n+ implementInterface = \"org.keycloak.models.map.role.MapRoleEntity\",\n+ inherits = \"org.keycloak.models.map.storage.hotRod.role.HotRodRoleEntity.AbstractHotRodRoleEntityDelegate\"\n+)\n+@ProtoDoc(\"@Indexed\")\n+public class HotRodRoleEntity extends AbstractHotRodEntity {\n+\n+ public static abstract class AbstractHotRodRoleEntityDelegate extends UpdatableHotRodEntityDelegateImpl<HotRodRoleEntity> implements MapRoleEntity {\n+\n+ @Override\n+ public String getId() {\n+ return getHotRodEntity().id;\n+ }\n+\n+ @Override\n+ public void setId(String id) {\n+ HotRodRoleEntity entity = getHotRodEntity();\n+ if (entity.id != null) throw new IllegalStateException(\"Id cannot be changed\");\n+ entity.id = id;\n+ entity.updated |= id != null;\n+ }\n+\n+ @Override\n+ public void setName(String name) {\n+ HotRodRoleEntity entity = getHotRodEntity();\n+ entity.updated |= ! Objects.equals(entity.name, name);\n+ entity.name = name;\n+ entity.nameLowercase = name == null ? null : name.toLowerCase();\n+ }\n+ }\n+\n+ @ProtoField(number = 1, required = true)\n+ public int entityVersion = 1;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 2, required = true)\n+ public String id;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 3)\n+ public String realmId;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 4)\n+ public String name;\n+\n+ /**\n+ * Lowercase interpretation of {@link #name} field. Infinispan doesn't support case-insensitive LIKE for non-analyzed fields.\n+ * Search on analyzed fields can be case-insensitive (based on used analyzer) but doesn't support ORDER BY analyzed field.\n+ */\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 5)\n+ public String nameLowercase;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = \\\"filename\\\"))\")\n+ @ProtoField(number = 6)\n+ public String description;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 7)\n+ public Boolean clientRole;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 8)\n+ public String clientId;\n+\n+ @ProtoField(number = 9)\n+ public Set<String> compositeRoles;\n+\n+ @ProtoField(number = 10)\n+ public Set<HotRodAttributeEntityNonIndexed> attributes;\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ return HotRodRoleEntityDelegate.entityEquals(this, o);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return HotRodRoleEntityDelegate.entityHashCode(this);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/resources/config/cacheConfig.xml", "new_path": "model/map-hot-rod/src/main/resources/config/cacheConfig.xml", "diff": "</indexing>\n<encoding media-type=\"application/x-protostream\"/>\n</distributed-cache>\n+ <distributed-cache name=\"roles\" mode=\"SYNC\">\n+ <indexing>\n+ <indexed-entities>\n+ <indexed-entity>kc.HotRodRoleEntity</indexed-entity>\n+ </indexed-entities>\n+ </indexing>\n+ <encoding media-type=\"application/x-protostream\"/>\n+ </distributed-cache>\n<distributed-cache name=\"users\" mode=\"SYNC\">\n<indexing>\n<indexed-entities>\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/resources/config/infinispan.xml", "new_path": "model/map-hot-rod/src/main/resources/config/infinispan.xml", "diff": "</indexing>\n<encoding media-type=\"application/x-protostream\"/>\n</distributed-cache>\n+ <distributed-cache name=\"roles\" mode=\"SYNC\">\n+ <indexing>\n+ <indexed-entities>\n+ <indexed-entity>kc.HotRodRoleEntity</indexed-entity>\n+ </indexed-entities>\n+ </indexing>\n+ <encoding media-type=\"application/x-protostream\"/>\n+ </distributed-cache>\n<distributed-cache name=\"users\" mode=\"SYNC\">\n<indexing>\n<indexed-entities>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json", "new_path": "testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json", "diff": "\"username\": \"${keycloak.connectionsHotRod.username:myuser}\",\n\"password\": \"${keycloak.connectionsHotRod.password:qwer1234!}\",\n\"enableSecurity\": \"${keycloak.connectionsHotRod.enableSecurity:true}\",\n- \"reindexCaches\": \"${keycloak.connectionsHotRod.reindexCaches:clients,groups,users}\"\n+ \"reindexCaches\": \"${keycloak.connectionsHotRod.reindexCaches:clients,groups,users,roles}\"\n}\n},\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/pom.xml", "new_path": "testsuite/integration-arquillian/tests/pom.xml", "diff": "<systemPropertyVariables>\n<keycloak.client.map.storage.provider>hotrod</keycloak.client.map.storage.provider>\n<keycloak.group.map.storage.provider>hotrod</keycloak.group.map.storage.provider>\n+ <keycloak.role.map.storage.provider>hotrod</keycloak.role.map.storage.provider>\n<keycloak.user.map.storage.provider>hotrod</keycloak.user.map.storage.provider>\n</systemPropertyVariables>\n</configuration>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/main/resources/hotrod/infinispan.xml", "new_path": "testsuite/model/src/main/resources/hotrod/infinispan.xml", "diff": "</indexing>\n<encoding media-type=\"application/x-protostream\"/>\n</distributed-cache>\n+ <distributed-cache name=\"roles\" mode=\"SYNC\">\n+ <indexing>\n+ <indexed-entities>\n+ <indexed-entity>kc.HotRodRoleEntity</indexed-entity>\n+ </indexed-entities>\n+ </indexing>\n+ <encoding media-type=\"application/x-protostream\"/>\n+ </distributed-cache>\n<distributed-cache name=\"users\" mode=\"SYNC\">\n<indexing>\n<indexed-entities>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/parameters/HotRodMapStorage.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/parameters/HotRodMapStorage.java", "diff": "@@ -77,7 +77,7 @@ public class HotRodMapStorage extends KeycloakModelParameters {\n.spi(\"clientScope\").provider(MapClientScopeProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n.spi(\"group\").provider(MapGroupProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, HotRodMapStorageProviderFactory.PROVIDER_ID)\n.spi(\"realm\").provider(MapRealmProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n- .spi(\"role\").provider(MapRoleProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n+ .spi(\"role\").provider(MapRoleProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, HotRodMapStorageProviderFactory.PROVIDER_ID)\n.spi(DeploymentStateSpi.NAME).provider(MapDeploymentStateProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n.spi(StoreFactorySpi.NAME).provider(MapAuthorizationStoreFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n.spi(\"user\").provider(MapUserProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, HotRodMapStorageProviderFactory.PROVIDER_ID)\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/role/RoleModelTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/role/RoleModelTest.java", "diff": "@@ -66,6 +66,7 @@ public class RoleModelTest extends KeycloakModelTest {\nrolesSubset = IntStream.range(0, 10)\n.boxed()\n.map(i -> session.roles().addRealmRole(realm, \"main-role-composite-\" + i))\n+ .peek(role -> role.setDescription(\"This is a description for \" + role.getName() + \" realm role.\"))\n.peek(mainRole::addCompositeRole)\n.map(RoleModel::getId)\n.collect(Collectors.toList());\n@@ -74,6 +75,7 @@ public class RoleModelTest extends KeycloakModelTest {\nrolesSubset.addAll(IntStream.range(10, 20)\n.boxed()\n.map(i -> session.roles().addClientRole(clientModel, \"main-role-composite-\" + i))\n+ .peek(role -> role.setDescription(\"This is a description for \" + role.getName() + \" client role.\"))\n.peek(mainRole::addCompositeRole)\n.map(RoleModel::getId)\n.collect(Collectors.toList()));\n@@ -202,6 +204,29 @@ public class RoleModelTest extends KeycloakModelTest {\ntestRolesWithIdsPaginationSearchQueries(this::getModelResult);\n}\n+ @Test\n+ public void testSearchRolesByDescription() {\n+ withRealm(realmId, (session, realm) -> {\n+ List<RoleModel> realmRolesByDescription = session.roles().searchForRolesStream(realm, \"This is a\", null, null).collect(Collectors.toList());\n+ assertThat(realmRolesByDescription, hasSize(10));\n+ realmRolesByDescription = session.roles().searchForRolesStream(realm, \"realm role.\", 5, null).collect(Collectors.toList());\n+ assertThat(realmRolesByDescription, hasSize(5));\n+ realmRolesByDescription = session.roles().searchForRolesStream(realm, \"DESCRIPTION FOR\", 3, 9).collect(Collectors.toList());\n+ assertThat(realmRolesByDescription, hasSize(7));\n+\n+ ClientModel client = session.clients().getClientByClientId(realm, \"client-with-roles\");\n+\n+ List<RoleModel> clientRolesByDescription = session.roles().searchForClientRolesStream(client, \"this is a\", 0, 10).collect(Collectors.toList());\n+ assertThat(clientRolesByDescription, hasSize(10));\n+\n+ clientRolesByDescription = session.roles().searchForClientRolesStream(client, \"role-composite-13 client role\", null, null).collect(Collectors.toList());\n+ assertThat(clientRolesByDescription, hasSize(1));\n+ assertThat(clientRolesByDescription.get(0).getDescription(), is(\"This is a description for main-role-composite-13 client role.\"));\n+\n+ return null;\n+ });\n+ }\n+\npublic void testRolesWithIdsPaginationSearchQueries(GetResult resultProvider) {\n// test all parameters together\nList<RoleModel> result = resultProvider.getResult(\"1\", 4, 3);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Hot Rod map storage: Roles no-downtime store
339,487
10.02.2022 16:25:25
10,800
442d9bae2effdca899f275d26748e6073e8aeb64
Add CockroachDB support in the new JPA storage Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/liquibase/extension/CreateJsonIndexGenerator.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/liquibase/extension/CreateJsonIndexGenerator.java", "diff": "@@ -21,6 +21,7 @@ import java.util.Arrays;\nimport java.util.stream.Collectors;\nimport liquibase.database.Database;\n+import liquibase.database.core.CockroachDatabase;\nimport liquibase.database.core.PostgresDatabase;\nimport liquibase.exception.ValidationErrors;\nimport liquibase.sql.Sql;\n@@ -96,8 +97,14 @@ public class CreateJsonIndexGenerator extends AbstractSqlGenerator<CreateJsonInd\n}\nprotected void handleJsonIndex(final CreateJsonIndexStatement statement, final Database database, final StringBuilder builder) {\n- if (database instanceof PostgresDatabase) {\n+ if (database instanceof CockroachDatabase) {\nbuilder.append(\" USING gin (\");\n+ builder.append(Arrays.stream(statement.getColumns()).map(JsonEnabledColumnConfig.class::cast)\n+ .map(c -> \"(\" + c.getJsonColumn() + \"->'\" + c.getJsonProperty() + \"')\")\n+ .collect(Collectors.joining(\", \")))\n+ .append(\")\");\n+ }\n+ else if (database instanceof PostgresDatabase) { builder.append(\" USING gin (\");\nbuilder.append(Arrays.stream(statement.getColumns()).map(JsonEnabledColumnConfig.class::cast)\n.map(c -> \"(\" + c.getJsonColumn() + \"->'\" + c.getJsonProperty() + \"') jsonb_path_ops\")\n.collect(Collectors.joining(\", \")))\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/liquibase/updater/MapJpaLiquibaseUpdaterProvider.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/liquibase/updater/MapJpaLiquibaseUpdaterProvider.java", "diff": "@@ -49,15 +49,19 @@ public class MapJpaLiquibaseUpdaterProvider implements MapJpaUpdaterProvider {\n@Override\npublic void update(Class modelType, Connection connection, String defaultSchema) {\n- update(modelType, connection, null, defaultSchema);\n+ synchronized (MapJpaLiquibaseUpdaterProvider.class) {\n+ this.updateSynch(modelType, connection, null, defaultSchema);\n+ }\n}\n@Override\npublic void export(Class modelType, Connection connection, String defaultSchema, File file) {\n- update(modelType, connection, file, defaultSchema);\n+ synchronized (MapJpaLiquibaseUpdaterProvider.class) {\n+ this.updateSynch(modelType, connection, file, defaultSchema);\n+ }\n}\n- private void update(Class modelType, Connection connection, File file, String defaultSchema) {\n+ protected void updateSynch(Class modelType, Connection connection, File file, String defaultSchema) {\nlogger.debug(\"Starting database update\");\n// Need ThreadLocal as liquibase doesn't seem to have API to inject custom objects into tasks\n@@ -113,6 +117,12 @@ public class MapJpaLiquibaseUpdaterProvider implements MapJpaUpdaterProvider {\n@Override\npublic Status validate(Class modelType, Connection connection, String defaultSchema) {\n+ synchronized (MapJpaLiquibaseUpdaterProvider.class) {\n+ return this.validateSynch(modelType, connection, defaultSchema);\n+ }\n+ }\n+\n+ protected Status validateSynch(final Class modelType, final Connection connection, final String defaultSchema) {\nlogger.debug(\"Validating if database is updated\");\nThreadLocalSessionContext.setCurrentSession(session);\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/client-scopes/jpa-client-scopes-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/client-scopes/jpa-client-scopes-changelog-1.xml", "diff": "@@ -22,7 +22,7 @@ limitations under the License.\nxsi:schemaLocation=\"http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd\nhttp://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd\">\n- <!-- format of id of changeSet: client-scopes-${org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_CLIENT_SCOPE} -->\n+ <!-- format of id of changeSet: client-scopes-${org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_CLIENT_SCOPE} -->\n<changeSet author=\"keycloak\" id=\"client-scopes-1\">\n<createTable tableName=\"kc_client_scope\">\n@@ -64,7 +64,7 @@ limitations under the License.\n<column name=\"name\"/>\n<column name=\"VALUE(255)\" valueComputed=\"VALUE(255)\"/>\n</createIndex>\n- <modifySql dbms=\"postgresql\">\n+ <modifySql dbms=\"postgresql,cockroachdb\">\n<replace replace=\"VALUE(255)\" with=\"(value::varchar(250))\"/>\n</modifySql>\n</changeSet>\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/clients/jpa-clients-changelog-1.xml", "diff": "@@ -22,7 +22,7 @@ limitations under the License.\nxsi:schemaLocation=\"http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd\nhttp://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd\">\n- <!-- format of id of changeSet: clients-${org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_CLIENT} -->\n+ <!-- format of id of changeSet: clients-${org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_CLIENT} -->\n<changeSet author=\"keycloak\" id=\"clients-1\">\n<createTable tableName=\"kc_client\">\n@@ -71,7 +71,7 @@ limitations under the License.\n<column name=\"name\"/>\n<column name=\"VALUE(255)\" valueComputed=\"VALUE(255)\"/>\n</createIndex>\n- <modifySql dbms=\"postgresql\">\n+ <modifySql dbms=\"postgresql,cockroachdb\">\n<replace replace=\"VALUE(255)\" with=\"(value::varchar(250))\"/>\n</modifySql>\n</changeSet>\n" }, { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/resources/META-INF/roles/jpa-roles-changelog-1.xml", "new_path": "model/map-jpa/src/main/resources/META-INF/roles/jpa-roles-changelog-1.xml", "diff": "@@ -22,7 +22,7 @@ limitations under the License.\nxsi:schemaLocation=\"http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd\nhttp://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd\">\n- <!-- format of id of changeSet: roles-${org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_ROLE} -->\n+ <!-- format of id of changeSet: roles-${org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_ROLE} -->\n<changeSet author=\"keycloak\" id=\"roles-1\">\n<createTable tableName=\"kc_role\">\n@@ -73,7 +73,7 @@ limitations under the License.\n<column name=\"name\"/>\n<column name=\"VALUE(255)\" valueComputed=\"VALUE(255)\"/>\n</createIndex>\n- <modifySql dbms=\"postgresql\">\n+ <modifySql dbms=\"postgresql,cockroachdb\">\n<replace replace=\"VALUE(255)\" with=\"(value::varchar(250))\"/>\n</modifySql>\n</changeSet>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add CockroachDB support in the new JPA storage Closes #10039
339,364
09.02.2022 12:23:45
-3,600
cfddcad3c574e1d732b756d8b67aef828b7bb842
Tests for Keycloak Deployment
[ { "change_type": "MODIFY", "old_path": "operator/src/test/java/org/keycloak/operator/ClusterOperatorTest.java", "new_path": "operator/src/test/java/org/keycloak/operator/ClusterOperatorTest.java", "diff": "@@ -12,15 +12,20 @@ import io.javaoperatorsdk.operator.api.reconciler.Reconciler;\nimport io.quarkiverse.operatorsdk.runtime.OperatorProducer;\nimport io.quarkiverse.operatorsdk.runtime.QuarkusConfigurationService;\nimport io.quarkus.logging.Log;\n+import org.awaitility.Awaitility;\nimport org.eclipse.microprofile.config.ConfigProvider;\nimport org.junit.jupiter.api.AfterAll;\nimport org.junit.jupiter.api.BeforeAll;\n+import org.junit.jupiter.api.BeforeEach;\nimport javax.enterprise.inject.Instance;\nimport javax.enterprise.inject.spi.CDI;\nimport javax.enterprise.util.TypeLiteral;\n+import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\n+import java.io.FileWriter;\n+import java.time.Duration;\nimport java.util.List;\nimport java.util.UUID;\n@@ -32,6 +37,9 @@ public abstract class ClusterOperatorTest {\npublic static final String OPERATOR_DEPLOYMENT_PROP = \"test.operator.deployment\";\npublic static final String TARGET_KUBERNETES_GENERATED_YML_FOLDER = \"target/kubernetes/\";\n+ public static final String TEST_RESULTS_DIR = \"target/operator-test-results/\";\n+ public static final String POD_LOGS_DIR = TEST_RESULTS_DIR + \"pod-logs/\";\n+\npublic enum OperatorDeployment {local,remote}\nprotected static OperatorDeployment operatorDeployment;\n@@ -50,6 +58,7 @@ public abstract class ClusterOperatorTest {\noperatorDeployment = ConfigProvider.getConfig().getOptionalValue(OPERATOR_DEPLOYMENT_PROP, OperatorDeployment.class).orElse(OperatorDeployment.local);\ndeploymentTarget = ConfigProvider.getConfig().getOptionalValue(QUARKUS_KUBERNETES_DEPLOYMENT_TARGET, String.class).orElse(\"kubernetes\");\n+ setDefaultAwaitilityTimings();\ncalculateNamespace();\ncreateK8sClient();\ncreateNamespace();\n@@ -63,6 +72,12 @@ public abstract class ClusterOperatorTest {\noperator.start();\n}\n+ deployDB();\n+ }\n+\n+ @BeforeEach\n+ public void beforeEach() {\n+ Log.info(((operatorDeployment == OperatorDeployment.remote) ? \"Remote \" : \"Local \") + \"Run Test :\" + namespace);\n}\nprivate static void createK8sClient() {\n@@ -122,6 +137,41 @@ public abstract class ClusterOperatorTest {\nnamespace = \"keycloak-test-\" + UUID.randomUUID();\n}\n+ protected static void deployDB() {\n+ // DB\n+ Log.info(\"Creating new PostgreSQL deployment\");\n+ k8sclient.load(KeycloakDeploymentE2EIT.class.getResourceAsStream(\"/example-postgres.yaml\")).inNamespace(namespace).createOrReplace();\n+\n+ // Check DB has deployed and ready\n+ Log.info(\"Checking Postgres is running\");\n+ Awaitility.await()\n+ .untilAsserted(() -> assertThat(k8sclient.apps().statefulSets().inNamespace(namespace).withName(\"postgresql-db\").get().getStatus().getReadyReplicas()).isEqualTo(1));\n+ }\n+\n+ // TODO improve this (preferably move to JOSDK)\n+ protected void savePodLogs() {\n+ Log.infof(\"Saving pod logs to %s\", POD_LOGS_DIR);\n+ for (var pod : k8sclient.pods().inNamespace(namespace).list().getItems()) {\n+ try {\n+ String podName = pod.getMetadata().getName();\n+ Log.infof(\"Processing %s\", podName);\n+ String podLog = k8sclient.pods().inNamespace(namespace).withName(podName).getLog();\n+ File file = new File(POD_LOGS_DIR + String.format(\"%s-%s.txt\", namespace, podName)); // using namespace for now, if more tests fail, the log might get overwritten\n+ file.getAbsoluteFile().getParentFile().mkdirs();\n+ try (var fw = new FileWriter(file, false)) {\n+ fw.write(podLog);\n+ }\n+ } catch (Exception e) {\n+ Log.error(e.getStackTrace());\n+ }\n+ }\n+ }\n+\n+ private static void setDefaultAwaitilityTimings() {\n+ Awaitility.setDefaultPollInterval(Duration.ofSeconds(1));\n+ Awaitility.setDefaultTimeout(Duration.ofSeconds(180));\n+ }\n+\n@AfterAll\npublic static void after() throws FileNotFoundException {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/test/java/org/keycloak/operator/KeycloakDeploymentE2EIT.java", "diff": "+package org.keycloak.operator;\n+\n+import io.fabric8.kubernetes.api.model.EnvVarBuilder;\n+import io.fabric8.kubernetes.api.model.apps.DeploymentSpecBuilder;\n+import io.quarkus.logging.Log;\n+import io.quarkus.test.junit.QuarkusTest;\n+import org.awaitility.Awaitility;\n+import org.junit.jupiter.api.AfterEach;\n+import org.junit.jupiter.api.Test;\n+import org.keycloak.operator.v2alpha1.crds.Keycloak;\n+\n+import java.time.Duration;\n+import java.util.List;\n+import java.util.Map;\n+\n+import static org.assertj.core.api.Assertions.assertThat;\n+import static org.keycloak.operator.utils.K8sUtils.deployKeycloak;\n+import static org.keycloak.operator.utils.K8sUtils.getDefaultKeycloakDeployment;\n+import static org.keycloak.operator.utils.K8sUtils.waitForKeycloakToBeReady;\n+\n+@QuarkusTest\n+public class KeycloakDeploymentE2EIT extends ClusterOperatorTest {\n+ @Test\n+ public void testBasicKeycloakDeploymentAndDeletion() {\n+ try {\n+ // CR\n+ Log.info(\"Creating new Keycloak CR example\");\n+ var kc = getDefaultKeycloakDeployment();\n+ var deploymentName = kc.getMetadata().getName();\n+ deployKeycloak(k8sclient, kc, true);\n+\n+ // Check Operator has deployed Keycloak\n+ Log.info(\"Checking Operator has deployed Keycloak deployment\");\n+ assertThat(k8sclient.apps().deployments().inNamespace(namespace).withName(deploymentName).get()).isNotNull();\n+\n+ // Check Keycloak has correct replicas\n+ Log.info(\"Checking Keycloak pod has ready replicas == 1\");\n+ assertThat(k8sclient.apps().deployments().inNamespace(namespace).withName(deploymentName).get().getStatus().getReadyReplicas()).isEqualTo(1);\n+\n+ // Delete CR\n+ Log.info(\"Deleting Keycloak CR and watching cleanup\");\n+ k8sclient.resources(Keycloak.class).delete(kc);\n+ Awaitility.await()\n+ .untilAsserted(() -> assertThat(k8sclient.apps().deployments().inNamespace(namespace).withName(deploymentName).get()).isNull());\n+ } catch (Exception e) {\n+ savePodLogs();\n+ throw e;\n+ }\n+ }\n+\n+ @Test\n+ public void testCRFields() {\n+ try {\n+ var kc = getDefaultKeycloakDeployment();\n+ var deploymentName = kc.getMetadata().getName();\n+ deployKeycloak(k8sclient, kc, true);\n+\n+ kc.getSpec().setImage(\"quay.io/keycloak/non-existing-keycloak\");\n+ kc.getSpec().getServerConfiguration().put(\"KC_DB_PASSWORD\", \"Ay Caramba!\");\n+ deployKeycloak(k8sclient, kc, false);\n+\n+ Awaitility.await()\n+ .during(Duration.ofSeconds(15)) // check if the Deployment is stable\n+ .untilAsserted(() -> {\n+ var c = k8sclient.apps().deployments().inNamespace(namespace).withName(deploymentName).get()\n+ .getSpec().getTemplate().getSpec().getContainers().get(0);\n+ assertThat(c.getImage()).isEqualTo(\"quay.io/keycloak/non-existing-keycloak\");\n+ assertThat(c.getEnv().stream()\n+ .anyMatch(e -> e.getName().equals(\"KC_DB_PASSWORD\") && e.getValue().equals(\"Ay Caramba!\")))\n+ .isTrue();\n+ });\n+\n+ } catch (Exception e) {\n+ savePodLogs();\n+ throw e;\n+ }\n+ }\n+\n+ @Test\n+ public void testDeploymentDurability() {\n+ try {\n+ var kc = getDefaultKeycloakDeployment();\n+ var deploymentName = kc.getMetadata().getName();\n+ deployKeycloak(k8sclient, kc, true);\n+\n+ Log.info(\"Trying to delete deployment\");\n+ assertThat(k8sclient.apps().deployments().withName(deploymentName).delete()).isTrue();\n+ Awaitility.await()\n+ .untilAsserted(() -> assertThat(k8sclient.apps().deployments().withName(deploymentName).get()).isNotNull());\n+\n+ waitForKeycloakToBeReady(k8sclient, kc); // wait for reconciler to calm down to avoid race condititon\n+\n+ Log.info(\"Trying to modify deployment\");\n+\n+ var deployment = k8sclient.apps().deployments().withName(deploymentName).get();\n+ var labels = Map.of(\"address\", \"EvergreenTerrace742\");\n+ var flandersEnvVar = new EnvVarBuilder().withName(\"NEIGHBOR\").withValue(\"Stupid Flanders!\").build();\n+ var origSpecs = new DeploymentSpecBuilder(deployment.getSpec()).build(); // deep copy\n+\n+ deployment.getMetadata().getLabels().putAll(labels);\n+ deployment.getSpec().getTemplate().getSpec().getContainers().get(0).setEnv(List.of(flandersEnvVar));\n+ k8sclient.apps().deployments().createOrReplace(deployment);\n+\n+ Awaitility.await()\n+ .untilAsserted(() -> {\n+ var d = k8sclient.apps().deployments().withName(deploymentName).get();\n+ assertThat(d.getMetadata().getLabels().entrySet().containsAll(labels.entrySet())).isTrue(); // additional labels should not be overwritten\n+ assertThat(d.getSpec()).isEqualTo(origSpecs); // specs should be reconciled back to original values\n+ });\n+ } catch (Exception e) {\n+ savePodLogs();\n+ throw e;\n+ }\n+ }\n+\n+ @AfterEach\n+ public void cleanup() {\n+ Log.info(\"Deleting Keycloak CR\");\n+ k8sclient.resources(Keycloak.class).delete(getDefaultKeycloakDeployment());\n+ }\n+\n+}\n" }, { "change_type": "DELETE", "old_path": "operator/src/test/java/org/keycloak/operator/OperatorE2EIT.java", "new_path": null, "diff": "-package org.keycloak.operator;\n-\n-import io.quarkus.logging.Log;\n-import io.quarkus.test.junit.QuarkusTest;\n-import org.awaitility.Awaitility;\n-import org.awaitility.core.ConditionTimeoutException;\n-import org.junit.jupiter.api.Test;\n-\n-import java.io.IOException;\n-import java.time.Duration;\n-\n-import static org.assertj.core.api.Assertions.assertThat;\n-\n-@QuarkusTest\n-public class OperatorE2EIT extends ClusterOperatorTest {\n- @Test\n- public void given_ClusterAndOperatorRunning_when_KeycloakCRCreated_Then_KeycloakStructureIsDeployedAndStatusIsOK() throws IOException {\n- Log.info(((operatorDeployment == OperatorDeployment.remote) ? \"Remote \" : \"Local \") + \"Run Test :\" + namespace);\n-\n- // DB\n- Log.info(\"Creating new PostgreSQL deployment\");\n- k8sclient.load(OperatorE2EIT.class.getResourceAsStream(\"/example-postgres.yaml\")).inNamespace(namespace).createOrReplace();\n-\n- // Check DB has deployed and ready\n- Log.info(\"Checking Postgres is running\");\n- Awaitility.await()\n- .atMost(Duration.ofSeconds(60))\n- .pollDelay(Duration.ofSeconds(2))\n- .untilAsserted(() -> assertThat(k8sclient.apps().statefulSets().inNamespace(namespace).withName(\"postgresql-db\").get().getStatus().getReadyReplicas()).isEqualTo(1));\n- // CR\n- Log.info(\"Creating new Keycloak CR example\");\n- k8sclient.load(OperatorE2EIT.class.getResourceAsStream(\"/example-keycloak.yml\")).inNamespace(namespace).createOrReplace();\n-\n- // Check Operator has deployed Keycloak\n- Log.info(\"Checking Operator has deployed Keycloak deployment\");\n- Awaitility.await()\n- .atMost(Duration.ofSeconds(60))\n- .pollDelay(Duration.ofSeconds(2))\n- .untilAsserted(() -> assertThat(k8sclient.apps().deployments().inNamespace(namespace).withName(\"example-kc\").get()).isNotNull());\n-\n- // Check Keycloak has status ready\n- StringBuffer podlog = new StringBuffer();\n- try {\n- Log.info(\"Checking Keycloak pod has ready replicas == 1\");\n- Awaitility.await()\n- .atMost(Duration.ofSeconds(180))\n- .pollDelay(Duration.ofSeconds(5))\n- .untilAsserted(() -> {\n- podlog.delete(0, podlog.length());\n- try {\n- k8sclient.pods().inNamespace(namespace).list().getItems().stream()\n- .filter(a -> a.getMetadata().getName().startsWith(\"example-kc\"))\n- .forEach(a -> podlog.append(a.getMetadata().getName()).append(\" : \")\n- .append(k8sclient.pods().inNamespace(namespace).withName(a.getMetadata().getName()).getLog(true)));\n- } catch (Exception e) {\n- // swallowing exception bc the pod is not ready to give logs yet\n- }\n- assertThat(k8sclient.apps().deployments().inNamespace(namespace).withName(\"example-kc\").get().getStatus().getReadyReplicas()).isEqualTo(1);\n- });\n- } catch (ConditionTimeoutException e) {\n- Log.error(\"On error POD LOG \" + podlog, e);\n- throw e;\n- }\n-\n-\n- }\n-\n-}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/test/java/org/keycloak/operator/utils/CRAssert.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.operator.utils;\n+\n+import org.keycloak.operator.v2alpha1.crds.Keycloak;\n+\n+import static org.assertj.core.api.Assertions.assertThat;\n+\n+/**\n+ * @author Vaclav Muzikar <[email protected]>\n+ */\n+public final class CRAssert {\n+ public static void assertKeycloakStatusCondition(Keycloak kc, String condition, boolean status) {\n+ assertThat(kc.getStatus().getConditions().stream()\n+ .anyMatch(c -> c.getType().equals(condition) && c.getStatus() == status)).isTrue();\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "operator/src/test/java/org/keycloak/operator/utils/K8sUtils.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.operator.utils;\n+\n+import io.fabric8.kubernetes.client.KubernetesClient;\n+import io.fabric8.kubernetes.client.utils.Serialization;\n+import io.quarkus.logging.Log;\n+import org.awaitility.Awaitility;\n+import org.keycloak.operator.v2alpha1.crds.Keycloak;\n+import org.keycloak.operator.v2alpha1.crds.KeycloakStatusCondition;\n+\n+import java.util.Collections;\n+import java.util.List;\n+import java.util.Objects;\n+\n+/**\n+ * @author Vaclav Muzikar <[email protected]>\n+ */\n+public final class K8sUtils {\n+ public static <T> T getResourceFromFile(String fileName) {\n+ return Serialization.unmarshal(Objects.requireNonNull(K8sUtils.class.getResourceAsStream(\"/\" + fileName)), Collections.emptyMap());\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ public static <T> T getResourceFromMultiResourceFile(String fileName, int index) {\n+ return ((List<T>) getResourceFromFile(fileName)).get(index);\n+ }\n+\n+ public static Keycloak getDefaultKeycloakDeployment() {\n+ return getResourceFromMultiResourceFile(\"example-keycloak.yml\", 0);\n+ }\n+\n+ public static void deployKeycloak(KubernetesClient client, Keycloak kc, boolean waitUntilReady) {\n+ client.resources(Keycloak.class).createOrReplace(kc);\n+\n+ if (waitUntilReady) {\n+ waitForKeycloakToBeReady(client, kc);\n+ }\n+ }\n+\n+ public static void deployDefaultKeycloak(KubernetesClient client) {\n+ deployKeycloak(client, getDefaultKeycloakDeployment(), true);\n+ }\n+\n+ public static void waitForKeycloakToBeReady(KubernetesClient client, Keycloak kc) {\n+ Log.infof(\"Waiting for Keycloak \\\"%s\\\"\", kc.getMetadata().getName());\n+ Awaitility.await()\n+ .ignoreExceptions()\n+ .untilAsserted(() -> {\n+ var currentKc = client.resources(Keycloak.class).withName(kc.getMetadata().getName()).get();\n+ CRAssert.assertKeycloakStatusCondition(currentKc, KeycloakStatusCondition.READY, true);\n+ CRAssert.assertKeycloakStatusCondition(currentKc, KeycloakStatusCondition.HAS_ERRORS, false);\n+ });\n+ }\n+}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Tests for Keycloak Deployment
339,410
08.02.2022 09:09:49
-3,600
d6cd69381b1b5e71b44d274e863419954f54cf8d
Add missing properties to keycloak-server.json for map storage Closes
[ { "change_type": "MODIFY", "old_path": "testsuite/utils/src/main/resources/META-INF/keycloak-server.json", "new_path": "testsuite/utils/src/main/resources/META-INF/keycloak-server.json", "diff": "\"authenticationSessions\": {\n\"provider\": \"${keycloak.authSession.provider:infinispan}\",\n+ \"map\": {\n+ \"storage\": {\n+ \"provider\": \"${keycloak.authSession.map.storage.provider:concurrenthashmap}\"\n+ }\n+ },\n\"infinispan\": {\n\"authSessionsLimit\": \"${keycloak.authSessions.limit:300}\"\n}\n},\n\"userSessions\": {\n- \"provider\": \"${keycloak.userSession.provider:infinispan}\"\n+ \"provider\": \"${keycloak.userSession.provider:infinispan}\",\n+ \"map\": {\n+ \"storage-user-sessions\": {\n+ \"provider\": \"${keycloak.userSession.map.storage.provider:concurrenthashmap}\"\n+ },\n+ \"storage-client-sessions\": {\n+ \"provider\": \"${keycloak.userSession.map.storage.provider:concurrenthashmap}\"\n+ }\n+ }\n},\n\"loginFailure\": {\n- \"provider\": \"${keycloak.loginFailure.provider:infinispan}\"\n+ \"provider\": \"${keycloak.loginFailure.provider:infinispan}\",\n+ \"map\": {\n+ \"storage\": {\n+ \"provider\": \"${keycloak.loginFailure.map.storage.provider:concurrenthashmap}\"\n+ }\n+ }\n},\n\"mapStorage\": {\n},\n\"authorizationPersister\": {\n- \"provider\": \"${keycloak.authorization.provider:jpa}\"\n+ \"provider\": \"${keycloak.authorization.provider:jpa}\",\n+ \"map\": {\n+ \"storage\": {\n+ \"provider\": \"${keycloak.authorization.map.storage.provider:concurrenthashmap}\"\n+ }\n+ }\n},\n\"theme\": {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add missing properties to keycloak-server.json for map storage Closes #10058
339,618
14.02.2022 16:03:03
-3,600
e1967250af3c2d53e3545d4a0bab47dbbefbfe1f
provide readme for containers module seems to accidentally gone missing when moving from containers repo Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "quarkus/container/README.md", "diff": "+# Keycloak Image\n+For more information, see the [Running Keycloak in a container guide](https://www.keycloak.org/guides/server/containers).\n+\n+## Build the image\n+\n+It is possible to download the Keycloak distribution from a URL:\n+\n+ docker build --build-arg KEYCLOAK_DIST=http://<HOST>:<PORT>/keycloak-<VERSION>.tar.gz . -t <YOUR_TAG>\n+\n+Alternatively, you need to build the local distribution first, then copy the distributions tar package in the `containers` folder and point the build command to use the image:\n+\n+ cp $KEYCLOAK_SOURCE/quarkus/dist/target/keycloak-<VERSION>.tar.gz .\n+ docker build --build-arg KEYCLOAK_DIST=keycloak-<VERSION>.tar.gz . -t <YOUR_TAG>\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
provide readme for containers module (#10093) seems to accidentally gone missing when moving from containers repo Closes #10092
339,618
11.02.2022 16:06:18
-3,600
5d781304e79137551234de81bc6fb71f451935c0
Fix idelauncher resourceloading caused by doubled slashes when getting the path for resources while running IDELauncher. So now we sanitize them. Tests by building and running wf and quarkus distribution, running from idelauncher and running using quarkus:dev, assets got always loaded. closes
[ { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/services/resources/QuarkusWelcomeResource.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/services/resources/QuarkusWelcomeResource.java", "diff": "@@ -65,8 +65,7 @@ import java.util.concurrent.atomic.AtomicBoolean;\n@Path(\"/\")\npublic class QuarkusWelcomeResource {\n- protected static final Logger logger = Logger.getLogger(WelcomeResource.class);\n-\n+ private static final Logger logger = Logger.getLogger(QuarkusWelcomeResource.class);\nprivate static final String KEYCLOAK_STATE_CHECKER = \"WELCOME_STATE_CHECKER\";\nprivate AtomicBoolean shouldBootstrap;\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/theme/ClassLoaderTheme.java", "new_path": "services/src/main/java/org/keycloak/theme/ClassLoaderTheme.java", "diff": "@@ -110,7 +110,13 @@ public class ClassLoaderTheme implements Theme {\nif (rootResourceURL == null) {\nreturn null;\n}\n- final String rootPath = rootResourceURL.getPath();\n+ String rootPath = rootResourceURL.getPath();\n+\n+ if (rootPath.endsWith(\"//\")) {\n+ // needed for asset loading in quarkus IDELauncher - see gh issue #9942\n+ rootPath = rootPath.substring(0, rootPath.length() -1);\n+ }\n+\nfinal URL resourceURL = classLoader.getResource(resourceRoot + path);\nif(resourceURL == null || !resourceURL.getPath().startsWith(rootPath)) {\nreturn null;\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Fix idelauncher resourceloading caused by doubled slashes when getting the path for resources while running IDELauncher. So now we sanitize them. Tests by building and running wf and quarkus distribution, running from idelauncher and running using quarkus:dev, assets got always loaded. closes #9942
339,190
14.02.2022 17:41:53
-3,600
909740ca5134edbb7b8f6431ed20ebac95d47647
Fix a wrong expiration placeholder in French email translations: emailVerificationBody and emailVerificationBodyHtml Closes
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources-community/theme/base/email/messages/messages_fr.properties", "new_path": "themes/src/main/resources-community/theme/base/email/messages/messages_fr.properties", "diff": "emailVerificationSubject=V\\u00e9rification du courriel\n-emailVerificationBody=Quelqu''un vient de cr\\u00e9er un compte \"{2}\" avec votre courriel. Si vous \\u00eates \\u00e0 l''origine de cette requ\\u00eate, veuillez cliquer sur le lien ci-dessous afin de v\\u00e9rifier votre adresse de courriel\\n\\n{0}\\n\\nCe lien expire dans {4}.\\n\\nSinon, veuillez ignorer ce message.\n-emailVerificationBodyHtml=<p>Quelqu''un vient de cr\\u00e9er un compte \"{2}\" avec votre courriel. Si vous \\u00eates \\u00e0 l''origine de cette requ\\u00eate, veuillez cliquer sur le lien ci-dessous afin de v\\u00e9rifier votre adresse de courriel</p><p><a href=\"{0}\">{0}</a></p><p>Ce lien expire dans {4}.</p><p>Sinon, veuillez ignorer ce message.</p>\n+emailVerificationBody=Quelqu''un vient de cr\\u00e9er un compte \"{2}\" avec votre courriel. Si vous \\u00eates \\u00e0 l''origine de cette requ\\u00eate, veuillez cliquer sur le lien ci-dessous afin de v\\u00e9rifier votre adresse de courriel\\n\\n{0}\\n\\nCe lien expire dans {3}.\\n\\nSinon, veuillez ignorer ce message.\n+emailVerificationBodyHtml=<p>Quelqu''un vient de cr\\u00e9er un compte \"{2}\" avec votre courriel. Si vous \\u00eates \\u00e0 l''origine de cette requ\\u00eate, veuillez cliquer sur le lien ci-dessous afin de v\\u00e9rifier votre adresse de courriel</p><p><a href=\"{0}\">{0}</a></p><p>Ce lien expire dans {3}.</p><p>Sinon, veuillez ignorer ce message.</p>\npasswordResetSubject=R\\u00e9initialiser le mot de passe\npasswordResetBody=Quelqu''un vient de demander une r\\u00e9initialisation de mot de passe pour votre compte {2}. Si vous \\u00eates \\u00e0 l''origine de cette requ\\u00eate, veuillez cliquer sur le lien ci-dessous pour le mettre \\u00e0 jour.\\n\\n{0}\\n\\nCe lien expire dans {3}.\\n\\nSinon, veuillez ignorer ce message ; aucun changement ne sera effectu\\u00e9 sur votre compte.\npasswordResetBodyHtml=<p>Quelqu''un vient de demander une r\\u00e9initialisation de mot de passe pour votre compte {2}. Si vous \\u00eates \\u00e0 l''origine de cette requ\\u00eate, veuillez cliquer sur le lien ci-dessous pour le mettre \\u00e0 jour.</p><p><a href=\"{0}\">Lien pour r\\u00e9initialiser votre mot de passe</a></p><p>Ce lien expire dans {3}.</p><p>Sinon, veuillez ignorer ce message ; aucun changement ne sera effectu\\u00e9 sur votre compte.</p>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Fix a wrong expiration placeholder in French email translations: emailVerificationBody and emailVerificationBodyHtml Closes #10136
339,410
27.01.2022 17:08:02
-3,600
50c783f4a9876daba3352a693d7636b4480c6495
Refactor test for readability and structure Closes
[ { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/infinispan/CacheExpirationTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/infinispan/CacheExpirationTest.java", "diff": "*/\npackage org.keycloak.testsuite.model.infinispan;\n-import org.hamcrest.Matchers;\nimport org.infinispan.Cache;\nimport org.junit.Assume;\nimport org.junit.Test;\n@@ -33,7 +32,6 @@ import java.util.Collections;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n-import java.util.concurrent.atomic.AtomicLong;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n@@ -51,9 +49,12 @@ import static org.junit.Assume.assumeThat;\n@RequireProvider(InfinispanConnectionProvider.class)\npublic class CacheExpirationTest extends KeycloakModelTest {\n+ public static final int NUM_EXTRA_FACTORIES = 4;\n+\n@Test\npublic void testCacheExpiration() throws Exception {\n- AtomicLong putTime = new AtomicLong();\n+\n+ log.debug(\"Put two events to the main cache\");\ninComittedTransaction(session -> {\nInfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\nCache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);\n@@ -61,59 +62,61 @@ public class CacheExpirationTest extends KeycloakModelTest {\n.filter(me -> me.getValue() instanceof AuthenticationSessionAuthNoteUpdateEvent)\n.forEach((c, me) -> c.remove(me.getKey()));\n- putTime.set(System.currentTimeMillis());\ncache.put(\"1-2\", AuthenticationSessionAuthNoteUpdateEvent.create(\"g1\", \"p1\", \"r1\", Collections.emptyMap()), 20000, TimeUnit.MILLISECONDS);\ncache.put(\"1-2-3\", AuthenticationSessionAuthNoteUpdateEvent.create(\"g2\", \"p2\", \"r2\", Collections.emptyMap()), 20000, TimeUnit.MILLISECONDS);\n});\nassumeThat(\"jmap output format unsupported\", getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class), notNullValue());\n+ // Ensure that instance counting works as expected, there should be at least two instances in memory now.\n// Infinispan server is decoding the client request before processing the request at the cache level,\n// therefore there are sometimes three instances of AuthenticationSessionAuthNoteUpdateEvent class in the memory\nassertThat(getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class), greaterThanOrEqualTo(2));\n- AtomicInteger maxCountOfInstances = new AtomicInteger();\n- AtomicInteger minCountOfInstances = new AtomicInteger(100);\n- inIndependentFactories(4, 5 * 60, () -> {\n+ log.debug(\"Starting other nodes and see that they join, receive the data and have their data expired\");\n+\n+ AtomicInteger completedTests = new AtomicInteger(0);\n+ inIndependentFactories(NUM_EXTRA_FACTORIES, 5 * 60, () -> {\nlog.debug(\"Joining the cluster\");\ninComittedTransaction(session -> {\nInfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\nCache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);\n+\n+ log.debug(\"Waiting for caches to join the cluster\");\ndo {\ntry { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n} while (! cache.getAdvancedCache().getDistributionManager().isJoinComplete());\n- cache.keySet().forEach(s -> {});\n- });\n- log.debug(\"Cluster joined\");\n- // access the items in the local cache in the different site (site-2) in order to fetch them from the remote cache\nString site = CONFIG.scope(\"connectionsInfinispan\", \"default\").get(\"siteName\");\n- if (\"site-2\".equals(site)) {\n- inComittedTransaction(session -> {\n- InfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\n- Cache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);\n- cache.get(\"1-2\");\n- cache.get(\"1-2-3\");\n- });\n- }\n- int c = getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class);\n- maxCountOfInstances.getAndAccumulate(c, Integer::max);\n- assumeThat(\"Seems we're running on a way too slow a computer\", System.currentTimeMillis() - putTime.get(), Matchers.lessThan(20000L));\n+ log.debug(\"Cluster joined \" + site);\n- // Wait for at most 3 minutes which is much more than 15 seconds expiration set in DefaultInfinispanConnectionProviderFactory\n- for (int i = 0; i < 3 * 60; i++) {\n+ log.debug(\"Waiting for cache to receive the two elements within the cluster\");\n+ do {\ntry { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n- if (getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class) == 0) {\n- break;\n- }\n- }\n+ } while (cache.entrySet().stream()\n+ .filter(me -> me.getValue() instanceof AuthenticationSessionAuthNoteUpdateEvent)\n+ .count() != 2);\n+\n+ // access the items in the local cache in the different site (site-2) in order to fetch them from the remote cache\n+ assertThat(cache.get(\"1-2\"), notNullValue());\n+ assertThat(cache.get(\"1-2-3\"), notNullValue());\n+\n+ // this is testing for a situation where an expiration lifespan configuration was missing in a replicated cache;\n+ // the elements were no longer seen in the cache, still they weren't garbage collected.\n+ // we must not look into the cache as that would trigger expiration explicitly.\n+ // original issue: https://issues.redhat.com/browse/KEYCLOAK-18518\n+ log.debug(\"Waiting for garbage collection to collect the entries across all caches in JVM\");\n+ do {\n+ try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n+ } while (getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class) != 0);\n- c = getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class);\n- minCountOfInstances.getAndAccumulate(c, Integer::min);\n+ completedTests.incrementAndGet();\n+ log.debug(\"Test completed\");\n+\n+ });\n});\n- assertThat(maxCountOfInstances.get(), is(10));\n- assertThat(minCountOfInstances.get(), is(0));\n+ assertThat(completedTests.get(), is(NUM_EXTRA_FACTORIES));\n}\nprivate static final Pattern JMAP_HOTSPOT_PATTERN = Pattern.compile(\"\\\\s*\\\\d+:\\\\s+(\\\\d+)\\\\s+(\\\\d+)\\\\s+(\\\\S+)\\\\s*\");\n@@ -124,9 +127,12 @@ public class CacheExpirationTest extends KeycloakModelTest {\nreturn getNumberOfInstancesOfClass(c, str[0]);\n}\n- public Integer getNumberOfInstancesOfClass(Class<?> c, String pid) {\n+ // This is synchronized as it doesn't make sense to run this in parallel with multiple threads\n+ // as each invocation will run a garbage collection anyway.\n+ public synchronized Integer getNumberOfInstancesOfClass(Class<?> c, String pid) {\nProcess proc;\ntry {\n+ // running this command will also trigger a garbage collection on the VM\nproc = Runtime.getRuntime().exec(\"jmap -histo:live \" + pid);\ntry (BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Refactor test for readability and structure Closes #9869
339,201
16.02.2022 13:49:17
-3,600
68ada40197df94daee6e624f696899f095189fc9
Remove keycloak-wildfly-adapter-dist from adapter bom The artifact is a zip-file. The definition in the bom doesn't set the type, so it defaults to jar which doesn't work. Fixes
[ { "change_type": "MODIFY", "old_path": "boms/adapter/pom.xml", "new_path": "boms/adapter/pom.xml", "diff": "<artifactId>keycloak-adapter-spi</artifactId>\n<version>${project.version}</version>\n</dependency>\n- <dependency>\n- <groupId>org.keycloak</groupId>\n- <artifactId>keycloak-wildfly-adapter-dist</artifactId>\n- <version>${project.version}</version>\n- </dependency>\n<dependency>\n<groupId>org.keycloak</groupId>\n<artifactId>keycloak-saml-adapter-core</artifactId>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Remove keycloak-wildfly-adapter-dist from adapter bom (#9346) The artifact is a zip-file. The definition in the bom doesn't set the type, so it defaults to jar which doesn't work. Fixes #9339
339,181
09.02.2022 21:46:19
18,000
19b637e8955635d0db76d31635891cf5c3b0f32d
Changing back to steps and removing extra space Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/configuration.adoc", "new_path": "docs/guides/src/main/server/configuration.adoc", "diff": "title=\"Configuring Keycloak\"\nsummary=\"An overview of the server configuration\">\n-In this guide, you will learn the core concepts around the server configuration and how to configure the server using the different\n-server options available. You will also learn how to properly configure the server to achieve an optimal runtime for faster\n-startup and low memory footprint.\n+This guide describes underlying core concepts of Keycloak configuration. It includes configuration guidelines for optimizing Keycloak for faster startup and low memory footprint.\n-== Understanding Server Options\n+== Server options\n-All the server options can be found by using the `help` option for individual commands:\n+You can view the server options by adding the `help` option for individual commands:\n-.Listing all build options\n+.Listing build options\n<@kc.build parameters=\"--help\"/>\n-.Listing all configuration options\n+.Listing configuration options\n<@kc.start parameters=\"--help\"/>\n-You can instead look at all the server options at <@links.server id=\"all-config\"/>.\n+Alternatively, you can see the server options at <@links.server id=\"all-config\"/>.\n-Server options are loaded from different sources in a specific order and they use different formats. If an option is defined in different sources the order of resolution is first in the list of:\n+Server options are loaded from different sources in a specific order and they use different formats. If an option is defined in different sources, the order of resolution is the order in the following table:\n|===\n|*Source* | *Format*\n@@ -52,57 +50,52 @@ export KC_DB_URL_HOST=mykeycloakdb\ndb-url-host=mykeycloakdb\n```\n-The configuration source and the corresponding format you should use is use-case specific. That decision depends on the platform the server is deployed to\n-as well as on the optimizations you can get for an optimal runtime. For instance, when deploying the server into Kubernetes you would probably rely\n-on environment variables to configure the server. However, you are not limited to use a single configuration source and format.\n+The configuration source and the corresponding format you should use is use-case specific. That decision depends on the platform where the server is deployed and the runtime optimizations you are seeking. For instance, if you deploy the server into Kubernetes, you would probably rely\n+on environment variables to configure the server. However, you are not limited to a single configuration source or format.\n-== Configuring the server\n+== Configuration commands and stages\n-The server options are narrowed to a specific command or configuration stage. This clear separation is one of the key aspects\n-of the server configuration and is related to a series of optimizations that are done in order to deliver the best runtime when starting and running the server.\n+The server options are narrowed to a specific command or configuration stage. The goal is to perform a series of optimizations in a specific order to achieve optimal startup and runtime performance. This configuration occurs in two stages:\n-Configuration is basically done in two stages:\n+First stage:: Configuration performed before starting the server in order to build an optimized server image for use at runtime\n+Second stage:: Configuration performed as part of starting the server\n-* Before starting the server in order to build an optimized server image for an optimal runtime\n-* When starting the server\n+=== First stage: Build an optimized Keycloak image\n-The first stage involves running the `build` command and set any **build option** available from this command to configure the server.\n+The first stage involves running the `build` command and setting any **build option** available from this command to configure the server.\n-By looking at the individual configuration options at <@links.server id=\"all-config\"/>, you notice\n-that some options are marked with an icon to indicate they are a build option. In other words, they can only be set and only take effect when running the `build` command.\n-You can also check all the options that require a build by looking at the `help` message of the `build` command:\n+The configuration options at <@links.server id=\"all-config\"/> include options that are marked with a tool icon. This icon indicates they are build options. Build options take effect only when you apply them to the `build` command.\n+\n+You can also check which options require a build by looking at the `help` message of the `build` command:\n<@kc.build parameters=\"--help\"/>\n-The `build` command is responsible for producing an immutable and optimized server image, which is similar to building a container image. In addition to persisting\n-any build option you have set, this command also performs a series of optimizations to deliver the best runtime when starting and running the server. As a result,\n-a lot of processing that would usually happen when starting and running the server is no longer necessary and the server can start and run faster.\n+The `build` command can produce an immutable and optimized server image, which is similar to building a container image. In addition to persisting build options, this command also performs optimizations for the best startup and runtime performance. The result is that much processing for starting and running the server is performed before starting Keycloak, so Keycloak is able to start up and run faster later on.\n-Some optimizations performed by the `build` command are:\n+The following are some optimizations performed by the `build` command:\n-* Closed-world assumption about installed providers, which means that no need to re-create the registry every time the server starts\n-* Configuration files are pre-parsed to reduce IO when starting the server\n-* Database specific resources are configured and prepared to run against a specific database vendor\n+* Closed-world assumption about installed providers, which means that no need exists to re-create the registry at every startup\n+* Configuration files are pre-parsed to reduce I/O when starting the server\n+* Database specific resources are configured and prepared to run against a certain database vendor\n* By persisting build options into the server image, the server does not perform any additional step to interpret configuration options and (re)configure itself\n-Once you run the `build` command, you won't need to set the same **build options** again when starting the server.\n-\n-.First stage, run the `build` command to set any build option\n+.Run the `build` command to set the database to PostgreSQL before startup:\n<@kc.build parameters=\"--db=postgres\"/>\n-The second stage involves starting the server using any **configuration option** available from the `start` command.\n+Once you run the `build` command, you do not need to set the same **build options** when you start the server.\n-.Second stage, run the `start` command to set any configuration option when starting the server\n-<@kc.start parameters=\"--db-url-host=keycloak-postgres --db-username=keycloak --db-password=change_me --hostname mykeycloak.acme.com\"/>\n+=== Second stage: Starting Keycloak\n-At this stage, you are free to set any value you want to any of the configuration options.\n+The second stage involves starting the server by using the `start` command and including **configuration options** with the appropriate values.\n-Be aware that you need to escape characters when invoking commands containing special shell characters such as `;` using the CLI, so you might want to set it in the configuration file instead.\n+.Run the `start` command to start the server while setting various database options\n+<@kc.start parameters=\"--db-url-host=keycloak-postgres --db-username=keycloak --db-password=change_me --hostname mykeycloak.acme.com\"/>\n+\n+Note that if you invoke commands containing special shell characters such as `;` using the CLI, you need to escape those characters. In that situation, you might choose to use the `keycloak.conf` file to set configuration options instead.\n-== Configuring the server for an optimal startup time\n+== Optimization by using a configuration file\n-In addition to the optimizations performed when you run the `build` command, you might want to avoid using CLI options when running the\n-`start` command in favor of using environment variables or configuration options from the `conf/keycloak.conf` file.\n+Most optimizations to startup and memory footprint can be achieved by using the `build` command. Additionally, you can use the `conf/keycloak.conf` file to set configuration options. Using this file avoids some necessary parsing steps when providing configuration options using the CLI or environment variables.\n.Set any build option\n<@kc.build parameters=\"--db=postgres\"/>\n@@ -118,25 +111,25 @@ hostname mykeycloak.acme.com\n.Start the server\n<@kc.start/>\n-By following that approach, the server is going to skip some steps at startup and start faster.\n+By using the `keycloak.conf` file, the server can omit some steps at startup. As a result, the server starts faster.\n-== Using the `auto-build` option when starting the server\n+== The auto-build option: automatic detection when the server needs a build\n-The `auto-build` option allows you to perform the two configuration stages using a single command. Under certain circumstances, you might want to sacrifice the server startup time and update the values of build options when starting the server.\n+Under certain circumstances, you might prefer to allow a longer startup time in favor of updating the values of build options when starting the server. Using the `auto-build` option, you can perform the two configuration stages by using a single command. Note that using `auto-build` is very likely to double the startup time for Keycloak. For most environments, this approach is not optimal.\n-For that, you can start the server as follows:\n+You start the server by entering the following command:\n.Using the `auto-build` option\n<@kc.start parameters=\"--auto-build --db postgres --db-url-host keycloak-postgres --db-username keycloak --db-password change_me --hostname mykeycloak.acme.com\"/>\n-By using this option, the server is going to calculate the build options that have changed and automatically runs the `build` command, if necessary, before starting the server.\n+By including the `auto-build` option, the server calculates the build options that have changed and runs the `build` command, if necessary, before starting the server.\n-== Configuring the server using configuration files\n+== Configuring the server by using configuration files\n-By default, the server is going to always fetch any configuration option you set from the `conf/keycloak.conf` file. When you are using a fresh distribution,\n-this file holds only the recommended settings for running in production, which are initially commented out.\n+By default, the server always fetches configuration options from the `conf/keycloak.conf` file. For a new installation,\n+this file holds only the recommended settings for running in production and those settings are commented out.\n-You can also specify a different configuration file by using the `[-cf|--config-file] option as follows:\n+You can also specify a different configuration file by using the `[-cf|--config-file] option by entering the following command:\n.Running the `build` command using a custom configuration file\n<@kc.build rootParameters=\"-cf myconfig.conf\"/>\n@@ -145,38 +138,35 @@ You can also specify a different configuration file by using the `[-cf|--config-\n<@kc.start rootParameters=\"-cf myconfig.conf\"/>\nChanges to any *build option* defined in the `keycloak.conf` file that is targeted for the `build` command are ignored\n-if the value differs from the value used to previously run the `build` command. In this case, make sure you run the `build` command again so that\n+if the value differs from the value for the last `build` command. In this case, make sure you run the `build` command again so that\nany build option is updated accordingly.\n-=== Understanding the development and production modes\n-\n-By default, the server defines two main operating modes:\n+=== Development versus production mode\n-* Development\n-* Production\n+The server supports the following operating modes:\n-The development mode is activated every time you run the `start-dev` command. In this mode, some key configuration options are set to make it possible to start the\n+Development mode:: This mode is activated every time you run the `start-dev` command. In this mode, some key configuration options are set to make it possible to start the\nserver for development purposes without the burden of having to define additional settings that are mandatory for production.\n-The production mode is activated by default when you run the `build` or the `start` command. Use this mode to set any configuration option that\n+Production mode:: This mode is activated when you run the `build` or `start` command. Use this mode to set any configuration option that\nis needed for deploying Keycloak in production.\n-By default, the configurations options for the production mode are commented out in the `conf/keycloak.conf`. These examples\n- are meant to give you an idea about the main settings that needs to be considered when running in production.\n+By default, the configuration options for the production mode are commented out in the `conf/keycloak.conf`. These examples\n+ are meant to give you an idea about the main settings to consider when running in production.\n-== Using unsupported server options\n+== Unsupported server options\n-Most of the time the available options from the server configuration should be enough to configure the server.\n-However, you might need to use properties directly from Quarkus in order to enable a specific behavior or capability that is missing from the server configuration.\n+In most cases, the available options from the server configuration should suffice to configure the server.\n+However, you might need to use properties directly from Quarkus to enable a specific behavior or capability that is missing from the server configuration.\n-You should avoid as much as possible using properties directly from Quarkus. If you really need to, consider opening an https://github.com/keycloak/keycloak/issues/new?assignees=&labels=kind%2Fenhancement%2Cstatus%2Ftriage&template=enhancement.yml[issue] first and help us\n+As much as possible, avoid using properties directly from Quarkus. If your need is essential, consider opening an https://github.com/keycloak/keycloak/issues/new?assignees=&labels=kind%2Fenhancement%2Cstatus%2Ftriage&template=enhancement.yml[issue] first and help us\nto improve the server configuration.\n-To configure the server using Quarkus properties you should follow these steps:\n+To configure the server using Quarkus properties, perform the following steps:\n-* Create a `conf/quarkus.properties` file and define any property you need\n-* Run the `build` command to apply the settings to the server\n+. Create a `conf/quarkus.properties` file and define any property you need.\n+. Run the `build` command to apply the settings to the server\n-For a complete list of Quarkus properties, consider looking at this https://quarkus.io/guides/all-config[documentation] .\n+For a complete list of Quarkus properties, see the https://quarkus.io/guides/all-config[Quarkus documentation] .\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Changing back to steps and removing extra space Closes #10100
339,472
02.11.2021 09:19:31
-25,200
31d8a927ff3f9737a59a10d72218c21dc7468bc3
moved create/update admin console event after commit, to prevent false alarm to event listeners
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/admin/UserResource.java", "new_path": "services/src/main/java/org/keycloak/services/resources/admin/UserResource.java", "diff": "@@ -188,11 +188,10 @@ public class UserResource {\nsession.getProvider(BruteForceProtector.class).cleanUpPermanentLockout(session, realm, user);\n}\n- adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();\n-\nif (session.getTransactionManager().isActive()) {\nsession.getTransactionManager().commit();\n}\n+ adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();\nreturn Response.noContent().build();\n} catch (ModelDuplicateException e) {\nreturn ErrorResponse.exists(\"User exists with same username or email\");\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java", "new_path": "services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java", "diff": "@@ -161,12 +161,11 @@ public class UsersResource {\nRepresentationToModel.createGroups(rep, realm, user);\nRepresentationToModel.createCredentials(rep, session, realm, user, true);\n- adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), user.getId()).representation(rep).success();\nif (session.getTransactionManager().isActive()) {\nsession.getTransactionManager().commit();\n}\n-\n+ adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), user.getId()).representation(rep).success();\nreturn Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(user.getId()).build()).build();\n} catch (ModelDuplicateException e) {\nif (session.getTransactionManager().isActive()) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-19602 moved create/update admin console event after commit, to prevent false alarm to event listeners
339,515
17.02.2022 11:42:20
-3,600
6c74aeec724fb76ff8b0051cc368ad29e749f787
docs: Change references from keycloak-x to keycloak
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/containers.adoc", "new_path": "docs/guides/src/main/server/containers.adoc", "diff": "@@ -19,14 +19,14 @@ The following `Dockerfile` creates a pre-configured Keycloak image that enables\n.Dockerfile:\n[source, dockerfile]\n----\n-FROM quay.io/keycloak/keycloak-x:latest as builder\n+FROM quay.io/keycloak/keycloak:latest as builder\nENV KC_METRICS_ENABLED=true\nENV KC_FEATURES=token-exchange\nENV KC_DB=postgres\nRUN /opt/keycloak/bin/kc.sh build\n-FROM quay.io/keycloak/keycloak-x:latest\n+FROM quay.io/keycloak/keycloak:latest\nCOPY --from=builder /opt/keycloak/lib/quarkus/ /opt/keycloak/lib/quarkus/\nWORKDIR /opt/keycloak\n# for demonstration purposes only, please make sure to use proper certificates in production instead\n@@ -81,7 +81,7 @@ You use the `start-dev` command:\n----\npodman|docker run --name keycloak_test -p 8080:8080 \\\n-e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=change_me \\\n- quay.io/keycloak/keycloak-x:latest \\\n+ quay.io/keycloak/keycloak:latest \\\nstart-dev\n----\n@@ -100,7 +100,7 @@ For example:\n----\npodman|docker run --name keycloak_auto_build -p 8080:8080 \\\n-e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=change_me \\\n- quay.io/keycloak/keycloak-x:latest \\\n+ quay.io/keycloak/keycloak:latest \\\nstart \\\n--auto-build \\\n--db=postgres --features=token-exchange \\\n" } ]
Java
Apache License 2.0
keycloak/keycloak
docs: Change references from keycloak-x to keycloak
339,204
17.02.2022 13:41:54
10,800
323c08c8cc81d7ad924754f0af335b0048e24a3e
Encryption algorithm RSA-OAEP with A256GCM Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "services/src/main/java/org/keycloak/keys/AbstractImportedRsaKeyProviderFactory.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.keys;\n+\n+import org.keycloak.common.util.CertificateUtils;\n+import org.keycloak.common.util.KeyUtils;\n+import org.keycloak.common.util.PemUtils;\n+import org.keycloak.component.ComponentModel;\n+import org.keycloak.component.ComponentValidationException;\n+import org.keycloak.crypto.KeyUse;\n+import org.keycloak.models.KeycloakSession;\n+import org.keycloak.models.RealmModel;\n+import org.keycloak.provider.ConfigurationValidationHelper;\n+import org.keycloak.provider.ProviderConfigurationBuilder;\n+\n+import java.security.KeyPair;\n+import java.security.PrivateKey;\n+import java.security.PublicKey;\n+import java.security.cert.Certificate;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Stian Thorgersen</a>\n+ * @author <a href=\"mailto:[email protected]\">Filipe Bojikian Rissi</a>\n+ */\n+public abstract class AbstractImportedRsaKeyProviderFactory extends AbstractRsaKeyProviderFactory {\n+\n+ public final static ProviderConfigurationBuilder rsaKeyConfigurationBuilder() {\n+ return ProviderConfigurationBuilder.create()\n+ .property(Attributes.PRIORITY_PROPERTY)\n+ .property(Attributes.ENABLED_PROPERTY)\n+ .property(Attributes.ACTIVE_PROPERTY)\n+ .property(Attributes.PRIVATE_KEY_PROPERTY)\n+ .property(Attributes.CERTIFICATE_PROPERTY);\n+ }\n+\n+ @Override\n+ public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException {\n+ ConfigurationValidationHelper.check(model)\n+ .checkLong(Attributes.PRIORITY_PROPERTY, false)\n+ .checkBoolean(Attributes.ENABLED_PROPERTY, false)\n+ .checkBoolean(Attributes.ACTIVE_PROPERTY, false)\n+ .checkSingle(Attributes.PRIVATE_KEY_PROPERTY, true)\n+ .checkSingle(Attributes.CERTIFICATE_PROPERTY, false);\n+\n+ KeyPair keyPair;\n+ try {\n+ PrivateKey privateKey = PemUtils.decodePrivateKey(model.get(Attributes.PRIVATE_KEY_KEY));\n+ PublicKey publicKey = KeyUtils.extractPublicKey(privateKey);\n+ keyPair = new KeyPair(publicKey, privateKey);\n+ } catch (Throwable t) {\n+ throw new ComponentValidationException(\"Failed to decode private key\", t);\n+ }\n+\n+ if (model.contains(Attributes.CERTIFICATE_KEY)) {\n+ Certificate certificate = null;\n+ try {\n+ certificate = PemUtils.decodeCertificate(model.get(Attributes.CERTIFICATE_KEY));\n+ } catch (Throwable t) {\n+ throw new ComponentValidationException(\"Failed to decode certificate\", t);\n+ }\n+\n+ if (certificate == null) {\n+ throw new ComponentValidationException(\"Failed to decode certificate\");\n+ }\n+\n+ if (!certificate.getPublicKey().equals(keyPair.getPublic())) {\n+ throw new ComponentValidationException(\"Certificate does not match private key\");\n+ }\n+ } else {\n+ try {\n+ Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, realm.getName());\n+ model.put(Attributes.CERTIFICATE_KEY, PemUtils.encodeCertificate(certificate));\n+ } catch (Throwable t) {\n+ throw new ComponentValidationException(\"Failed to generate self-signed certificate\");\n+ }\n+ }\n+ }\n+\n+ abstract protected boolean isValidKeyUse(KeyUse keyUse);\n+\n+ abstract protected boolean isSupportedRsaAlgorithm(String algorithm);\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/keys/AbstractRsaKeyProvider.java", "new_path": "services/src/main/java/org/keycloak/keys/AbstractRsaKeyProvider.java", "diff": "@@ -20,6 +20,7 @@ package org.keycloak.keys;\nimport org.keycloak.common.util.KeyUtils;\nimport org.keycloak.component.ComponentModel;\nimport org.keycloak.crypto.*;\n+import org.keycloak.jose.jwe.JWEConstants;\nimport org.keycloak.models.RealmModel;\nimport java.security.KeyPair;\n@@ -44,7 +45,9 @@ public abstract class AbstractRsaKeyProvider implements KeyProvider {\npublic AbstractRsaKeyProvider(RealmModel realm, ComponentModel model) {\nthis.model = model;\nthis.status = KeyStatus.from(model.get(Attributes.ACTIVE_KEY, true), model.get(Attributes.ENABLED_KEY, true));\n- this.algorithm = model.get(Attributes.ALGORITHM_KEY, Algorithm.RS256);\n+\n+ String defaultAlgorithmKey = KeyUse.ENC.name().equals(model.get(Attributes.KEY_USE)) ? JWEConstants.RSA_OAEP : Algorithm.RS256;\n+ this.algorithm = model.get(Attributes.ALGORITHM_KEY, defaultAlgorithmKey);\nif (model.hasNote(KeyWrapper.class.getName())) {\nkey = model.getNote(KeyWrapper.class.getName());\n" }, { "change_type": "ADD", "old_path": null, "new_path": "services/src/main/java/org/keycloak/keys/ImportedRsaEncKeyProviderFactory.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.keys;\n+\n+import org.keycloak.component.ComponentModel;\n+import org.keycloak.crypto.KeyUse;\n+import org.keycloak.jose.jwe.JWEConstants;\n+import org.keycloak.models.KeycloakSession;\n+import org.keycloak.provider.ProviderConfigProperty;\n+\n+import java.util.List;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Filipe Bojikian Rissi</a>\n+ */\n+public class ImportedRsaEncKeyProviderFactory extends AbstractImportedRsaKeyProviderFactory {\n+\n+ public static final String ID = \"rsa-enc\";\n+\n+ private static final String HELP_TEXT = \"RSA for key encryption provider that can optionally generated a self-signed certificate\";\n+\n+ private static final List<ProviderConfigProperty> CONFIG_PROPERTIES = AbstractImportedRsaKeyProviderFactory.rsaKeyConfigurationBuilder()\n+ .property(Attributes.RS_ENC_ALGORITHM_PROPERTY)\n+ .build();\n+\n+ @Override\n+ public KeyProvider create(KeycloakSession session, ComponentModel model) {\n+ model.put(Attributes.KEY_USE, KeyUse.ENC.name());\n+ return new ImportedRsaKeyProvider(session.getContext().getRealm(), model);\n+ }\n+\n+ @Override\n+ public String getHelpText() {\n+ return HELP_TEXT;\n+ }\n+\n+ @Override\n+ public List<ProviderConfigProperty> getConfigProperties() {\n+ return CONFIG_PROPERTIES;\n+ }\n+\n+ @Override\n+ protected boolean isValidKeyUse(KeyUse keyUse) {\n+ return keyUse.equals(KeyUse.ENC);\n+ }\n+\n+ @Override\n+ protected boolean isSupportedRsaAlgorithm(String algorithm) {\n+ return algorithm.equals(JWEConstants.RSA1_5)\n+ || algorithm.equals(JWEConstants.RSA_OAEP)\n+ || algorithm.equals(JWEConstants.RSA_OAEP_256);\n+ }\n+\n+ @Override\n+ public String getId() {\n+ return ID;\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/keys/ImportedRsaKeyProviderFactory.java", "new_path": "services/src/main/java/org/keycloak/keys/ImportedRsaKeyProviderFactory.java", "diff": "package org.keycloak.keys;\n-import org.keycloak.common.util.CertificateUtils;\n-import org.keycloak.common.util.KeyUtils;\n-import org.keycloak.common.util.PemUtils;\nimport org.keycloak.component.ComponentModel;\n-import org.keycloak.component.ComponentValidationException;\n+import org.keycloak.crypto.Algorithm;\n+import org.keycloak.crypto.KeyUse;\nimport org.keycloak.models.KeycloakSession;\n-import org.keycloak.models.RealmModel;\n-import org.keycloak.provider.ConfigurationValidationHelper;\nimport org.keycloak.provider.ProviderConfigProperty;\n-import java.security.KeyPair;\n-import java.security.PrivateKey;\n-import java.security.PublicKey;\n-import java.security.cert.Certificate;\nimport java.util.List;\n/**\n* @author <a href=\"mailto:[email protected]\">Stian Thorgersen</a>\n*/\n-public class ImportedRsaKeyProviderFactory extends AbstractRsaKeyProviderFactory {\n+public class ImportedRsaKeyProviderFactory extends AbstractImportedRsaKeyProviderFactory {\npublic static final String ID = \"rsa\";\n- private static final String HELP_TEXT = \"RSA key provider that can optionally generated a self-signed certificate\";\n+ private static final String HELP_TEXT = \"RSA signature key provider that can optionally generated a self-signed certificate\";\n- private static final List<ProviderConfigProperty> CONFIG_PROPERTIES = AbstractRsaKeyProviderFactory.configurationBuilder()\n- .property(Attributes.PRIVATE_KEY_PROPERTY)\n- .property(Attributes.CERTIFICATE_PROPERTY)\n- .property(Attributes.KEY_USE_PROPERTY)\n+ private static final List<ProviderConfigProperty> CONFIG_PROPERTIES = AbstractImportedRsaKeyProviderFactory.rsaKeyConfigurationBuilder()\n+ .property(Attributes.RS_ALGORITHM_PROPERTY)\n.build();\n@Override\npublic KeyProvider create(KeycloakSession session, ComponentModel model) {\n+ if (model.getConfig().get(Attributes.KEY_USE) == null) {\n+ // for backward compatibility : it allows \"enc\" key use for \"rsa\" provider\n+ model.put(Attributes.KEY_USE, KeyUse.SIG.name());\n+ }\nreturn new ImportedRsaKeyProvider(session.getContext().getRealm(), model);\n}\n@Override\n- public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException {\n- super.validateConfiguration(session, realm, model);\n-\n- ConfigurationValidationHelper.check(model)\n- .checkSingle(Attributes.PRIVATE_KEY_PROPERTY, true)\n- .checkSingle(Attributes.CERTIFICATE_PROPERTY, false);\n-\n- KeyPair keyPair;\n- try {\n- PrivateKey privateKey = PemUtils.decodePrivateKey(model.get(Attributes.PRIVATE_KEY_KEY));\n- PublicKey publicKey = KeyUtils.extractPublicKey(privateKey);\n- keyPair = new KeyPair(publicKey, privateKey);\n- } catch (Throwable t) {\n- throw new ComponentValidationException(\"Failed to decode private key\", t);\n- }\n-\n- if (model.contains(Attributes.CERTIFICATE_KEY)) {\n- Certificate certificate = null;\n- try {\n- certificate = PemUtils.decodeCertificate(model.get(Attributes.CERTIFICATE_KEY));\n- } catch (Throwable t) {\n- throw new ComponentValidationException(\"Failed to decode certificate\", t);\n- }\n-\n- if (certificate == null) {\n- throw new ComponentValidationException(\"Failed to decode certificate\");\n+ public String getHelpText() {\n+ return HELP_TEXT;\n}\n- if (!certificate.getPublicKey().equals(keyPair.getPublic())) {\n- throw new ComponentValidationException(\"Certificate does not match private key\");\n- }\n- } else {\n- try {\n- Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, realm.getName());\n- model.put(Attributes.CERTIFICATE_KEY, PemUtils.encodeCertificate(certificate));\n- } catch (Throwable t) {\n- throw new ComponentValidationException(\"Failed to generate self-signed certificate\");\n- }\n- }\n+ @Override\n+ public List<ProviderConfigProperty> getConfigProperties() {\n+ return CONFIG_PROPERTIES;\n}\n@Override\n- public String getHelpText() {\n- return HELP_TEXT;\n+ protected boolean isValidKeyUse(KeyUse keyUse) {\n+ return keyUse.equals(KeyUse.SIG);\n}\n@Override\n- public List<ProviderConfigProperty> getConfigProperties() {\n- return CONFIG_PROPERTIES;\n+ protected boolean isSupportedRsaAlgorithm(String algorithm) {\n+ return algorithm.equals(Algorithm.RS256)\n+ || algorithm.equals(Algorithm.PS256)\n+ || algorithm.equals(Algorithm.RS384)\n+ || algorithm.equals(Algorithm.PS384)\n+ || algorithm.equals(Algorithm.RS512)\n+ || algorithm.equals(Algorithm.PS512);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/resources/META-INF/services/org.keycloak.keys.KeyProviderFactory", "new_path": "services/src/main/resources/META-INF/services/org.keycloak.keys.KeyProviderFactory", "diff": "@@ -22,3 +22,4 @@ org.keycloak.keys.JavaKeystoreKeyProviderFactory\norg.keycloak.keys.ImportedRsaKeyProviderFactory\norg.keycloak.keys.GeneratedEcdsaKeyProviderFactory\norg.keycloak.keys.GeneratedRsaEncKeyProviderFactory\n+org.keycloak.keys.ImportedRsaEncKeyProviderFactory\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/keys/ImportedRsaKeyProviderTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/keys/ImportedRsaKeyProviderTest.java", "diff": "@@ -25,10 +25,12 @@ import org.keycloak.common.util.KeyUtils;\nimport org.keycloak.common.util.MultivaluedHashMap;\nimport org.keycloak.common.util.PemUtils;\nimport org.keycloak.crypto.Algorithm;\n+import org.keycloak.crypto.KeyUse;\n+import org.keycloak.jose.jwe.JWEConstants;\nimport org.keycloak.jose.jws.AlgorithmType;\nimport org.keycloak.keys.Attributes;\n+import org.keycloak.keys.ImportedRsaEncKeyProviderFactory;\nimport org.keycloak.keys.ImportedRsaKeyProviderFactory;\n-import org.keycloak.keys.KeyMetadata;\nimport org.keycloak.keys.KeyProvider;\nimport org.keycloak.representations.idm.ComponentRepresentation;\nimport org.keycloak.representations.idm.ErrorRepresentation;\n@@ -69,13 +71,22 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\n}\n@Test\n- public void privateKeyOnly() throws Exception {\n+ public void privateKeyOnlyForSig() throws Exception {\n+ privateKeyOnly(ImportedRsaKeyProviderFactory.ID, KeyUse.SIG, Algorithm.RS256);\n+ }\n+\n+ @Test\n+ public void privateKeyOnlyForEnc() throws Exception {\n+ privateKeyOnly(ImportedRsaEncKeyProviderFactory.ID, KeyUse.ENC, JWEConstants.RSA_OAEP);\n+ }\n+\n+ private void privateKeyOnly(String providerId, KeyUse keyUse, String algorithm) throws Exception {\nlong priority = System.currentTimeMillis();\nKeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);\nString kid = KeyUtils.createKeyId(keyPair.getPublic());\n- ComponentRepresentation rep = createRep(\"valid\", ImportedRsaKeyProviderFactory.ID);\n+ ComponentRepresentation rep = createRep(\"valid\", providerId);\nrep.getConfig().putSingle(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));\nrep.getConfig().putSingle(Attributes.PRIORITY_KEY, Long.toString(priority));\n@@ -91,7 +102,7 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\nKeysMetadataRepresentation keys = adminClient.realm(\"test\").keys().getKeyMetadata();\n- assertEquals(kid, keys.getActive().get(Algorithm.RS256));\n+ assertEquals(kid, keys.getActive().get(algorithm));\nKeysMetadataRepresentation.KeyMetadataRepresentation key = keys.getKeys().get(0);\n@@ -101,17 +112,27 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\nassertEquals(kid, key.getKid());\nassertEquals(PemUtils.encodeKey(keyPair.getPublic()), keys.getKeys().get(0).getPublicKey());\nassertEquals(keyPair.getPublic(), PemUtils.decodeCertificate(key.getCertificate()).getPublicKey());\n+ assertEquals(keyUse, keys.getKeys().get(0).getUse());\n}\n@Test\n- public void keyAndCertificate() throws Exception {\n+ public void keyAndCertificateForSig() throws Exception {\n+ keyAndCertificate(ImportedRsaKeyProviderFactory.ID, KeyUse.SIG);\n+ }\n+\n+ @Test\n+ public void keyAndCertificateForEnc() throws Exception {\n+ keyAndCertificate(ImportedRsaEncKeyProviderFactory.ID, KeyUse.ENC);\n+ }\n+\n+ private void keyAndCertificate(String providerId, KeyUse keyUse) throws Exception {\nlong priority = System.currentTimeMillis();\nKeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);\nCertificate certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, \"test\");\nString certificatePem = PemUtils.encodeCertificate(certificate);\n- ComponentRepresentation rep = createRep(\"valid\", ImportedRsaKeyProviderFactory.ID);\n+ ComponentRepresentation rep = createRep(\"valid\", providerId);\nrep.getConfig().putSingle(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));\nrep.getConfig().putSingle(Attributes.CERTIFICATE_KEY, certificatePem);\nrep.getConfig().putSingle(Attributes.PRIORITY_KEY, Long.toString(priority));\n@@ -128,13 +149,23 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\nKeysMetadataRepresentation.KeyMetadataRepresentation key = keys.getKeys().get(0);\nassertEquals(certificatePem, key.getCertificate());\n+ assertEquals(keyUse, keys.getKeys().get(0).getUse());\n}\n@Test\n- public void invalidPriority() throws Exception {\n+ public void invalidPriorityForSig() throws Exception {\n+ invalidPriority(ImportedRsaKeyProviderFactory.ID);\n+ }\n+\n+ @Test\n+ public void invalidPriorityForEnc() throws Exception {\n+ invalidPriority(ImportedRsaEncKeyProviderFactory.ID);\n+ }\n+\n+ private void invalidPriority(String providerId) throws Exception {\nKeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);\n- ComponentRepresentation rep = createRep(\"invalid\", ImportedRsaKeyProviderFactory.ID);\n+ ComponentRepresentation rep = createRep(\"invalid\", providerId);\nrep.getConfig().putSingle(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));\nrep.getConfig().putSingle(Attributes.PRIORITY_KEY, \"invalid\");\n@@ -143,10 +174,19 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\n}\n@Test\n- public void invalidEnabled() throws Exception {\n+ public void invalidEnabledForSig() throws Exception {\n+ invalidEnabled(ImportedRsaKeyProviderFactory.ID);\n+ }\n+\n+ @Test\n+ public void invalidEnabledForEnc() throws Exception {\n+ invalidEnabled(ImportedRsaEncKeyProviderFactory.ID);\n+ }\n+\n+ private void invalidEnabled(String providerId) throws Exception {\nKeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);\n- ComponentRepresentation rep = createRep(\"invalid\", ImportedRsaKeyProviderFactory.ID);\n+ ComponentRepresentation rep = createRep(\"invalid\", providerId);\nrep.getConfig().putSingle(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));\nrep.getConfig().putSingle(Attributes.ENABLED_KEY, \"invalid\");\n@@ -155,10 +195,19 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\n}\n@Test\n- public void invalidActive() throws Exception {\n+ public void invalidActiveForSig() throws Exception {\n+ invalidActive(ImportedRsaKeyProviderFactory.ID);\n+ }\n+\n+ @Test\n+ public void invalidActiveForEnc() throws Exception {\n+ invalidActive(ImportedRsaEncKeyProviderFactory.ID);\n+ }\n+\n+ private void invalidActive(String providerId) throws Exception {\nKeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);\n- ComponentRepresentation rep = createRep(\"invalid\", ImportedRsaKeyProviderFactory.ID);\n+ ComponentRepresentation rep = createRep(\"invalid\", providerId);\nrep.getConfig().putSingle(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));\nrep.getConfig().putSingle(Attributes.ACTIVE_KEY, \"invalid\");\n@@ -167,10 +216,19 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\n}\n@Test\n- public void invalidPrivateKey() throws Exception {\n+ public void invalidPrivateKeyForSig() throws Exception {\n+ invalidPrivateKey(ImportedRsaKeyProviderFactory.ID);\n+ }\n+\n+ @Test\n+ public void invalidPrivateKeyForEnc() throws Exception {\n+ invalidPrivateKey(ImportedRsaEncKeyProviderFactory.ID);\n+ }\n+\n+ private void invalidPrivateKey(String providerId) throws Exception {\nKeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);\n- ComponentRepresentation rep = createRep(\"invalid\", ImportedRsaKeyProviderFactory.ID);\n+ ComponentRepresentation rep = createRep(\"invalid\", providerId);\nResponse response = adminClient.realm(\"test\").components().add(rep);\nassertErrror(response, \"'Private RSA Key' is required\");\n@@ -185,11 +243,20 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {\n}\n@Test\n- public void invalidCertificate() throws Exception {\n+ public void invalidCertificateForSig() throws Exception {\n+ invalidCertificate(ImportedRsaKeyProviderFactory.ID);\n+ }\n+\n+ @Test\n+ public void invalidCertificateForEnc() throws Exception {\n+ invalidCertificate(ImportedRsaEncKeyProviderFactory.ID);\n+ }\n+\n+ private void invalidCertificate(String providerId) throws Exception {\nKeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);\nCertificate invalidCertificate = CertificateUtils.generateV1SelfSignedCertificate(KeyUtils.generateRsaKeyPair(2048), \"test\");\n- ComponentRepresentation rep = createRep(\"invalid\", ImportedRsaKeyProviderFactory.ID);\n+ ComponentRepresentation rep = createRep(\"invalid\", providerId);\nrep.getConfig().putSingle(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));\nrep.getConfig().putSingle(Attributes.CERTIFICATE_KEY, \"nonsense\");\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-19519 Encryption algorithm RSA-OAEP with A256GCM (#8553) Closes #10300
339,465
18.02.2022 11:33:31
-3,600
caf37b1f709957a41f5b2ffe0040873946dacc85
Support for acr_values_supported in OIDC well-known endpoint * Support for acr_values_supported in OIDC well-known endpoint closes
[ { "change_type": "MODIFY", "old_path": "core/src/main/java/org/keycloak/protocol/oidc/representations/OIDCConfigurationRepresentation.java", "new_path": "core/src/main/java/org/keycloak/protocol/oidc/representations/OIDCConfigurationRepresentation.java", "diff": "@@ -64,6 +64,9 @@ public class OIDCConfigurationRepresentation {\n@JsonProperty(\"grant_types_supported\")\nprivate List<String> grantTypesSupported;\n+ @JsonProperty(\"acr_values_supported\")\n+ private List<String> acrValuesSupported;\n+\n@JsonProperty(\"response_types_supported\")\nprivate List<String> responseTypesSupported;\n@@ -258,6 +261,14 @@ public class OIDCConfigurationRepresentation {\nthis.grantTypesSupported = grantTypesSupported;\n}\n+ public List<String> getAcrValuesSupported() {\n+ return acrValuesSupported;\n+ }\n+\n+ public void setAcrValuesSupported(List<String> acrValuesSupported) {\n+ this.acrValuesSupported = acrValuesSupported;\n+ }\n+\npublic List<String> getResponseTypesSupported() {\nreturn responseTypesSupported;\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/AuthenticatorUtil.java", "new_path": "services/src/main/java/org/keycloak/authentication/AuthenticatorUtil.java", "diff": "package org.keycloak.authentication;\nimport com.google.common.collect.Sets;\n+import org.jboss.logging.Logger;\n+import org.keycloak.authentication.authenticators.conditional.ConditionalLoaAuthenticator;\n+import org.keycloak.authentication.authenticators.conditional.ConditionalLoaAuthenticatorFactory;\nimport org.keycloak.models.AuthenticatedClientSessionModel;\n+import org.keycloak.models.AuthenticationExecutionModel;\n+import org.keycloak.models.AuthenticatorConfigModel;\nimport org.keycloak.models.Constants;\n+import org.keycloak.models.RealmModel;\nimport org.keycloak.sessions.AuthenticationSessionModel;\nimport org.keycloak.utils.StringUtil;\nimport java.util.Collections;\n+import java.util.LinkedList;\n+import java.util.List;\n+import java.util.Objects;\nimport java.util.Set;\n+import java.util.stream.Stream;\nimport static org.keycloak.services.managers.AuthenticationManager.SSO_AUTH;\npublic class AuthenticatorUtil {\n+ private static final Logger logger = Logger.getLogger(AuthenticatorUtil.class);\n+\n// It is used for identification of note included in authentication session for storing callback provider factories\npublic static String CALLBACKS_FACTORY_IDS_NOTE = \"callbacksFactoryProviderIds\";\n@@ -103,4 +115,54 @@ public class AuthenticatorUtil {\nreturn Collections.emptySet();\n}\n}\n+\n+\n+ /**\n+ * @param realm\n+ * @param flowId\n+ * @param providerId\n+ * @return all executions of given \"provider_id\" type. This is deep (recursive) obtain of executions of the particular flow\n+ */\n+ public static List<AuthenticationExecutionModel> getExecutionsByType(RealmModel realm, String flowId, String providerId) {\n+ List<AuthenticationExecutionModel> executions = new LinkedList<>();\n+ realm.getAuthenticationExecutionsStream(flowId).forEach(authExecution -> {\n+ if (providerId.equals(authExecution.getAuthenticator())) {\n+ executions.add(authExecution);\n+ } else if (authExecution.isAuthenticatorFlow() && authExecution.getFlowId() != null) {\n+ executions.addAll(getExecutionsByType(realm, authExecution.getFlowId(), providerId));\n+ }\n+ });\n+ return executions;\n+ }\n+\n+ /**\n+ * @param realm\n+ * @return All LoA numbers configured in the conditions in the realm browser flow\n+ */\n+ public static Stream<Integer> getLoAConfiguredInRealmBrowserFlow(RealmModel realm) {\n+ List<AuthenticationExecutionModel> loaConditions = getExecutionsByType(realm, realm.getBrowserFlow().getId(), ConditionalLoaAuthenticatorFactory.PROVIDER_ID);\n+ if (loaConditions.isEmpty()) {\n+ // Default values used when step-up conditions not used in the browser authentication flow.\n+ // This is used for backwards compatibility and in case when step-up is not configured in the authentication flow (returning 1 in case of \"normal\" authentication, 0 for SSO authentication)\n+ return Stream.of(Constants.MINIMUM_LOA, 1);\n+ } else {\n+ Stream<Integer> configuredLoas = loaConditions.stream()\n+ .map(authExecution -> realm.getAuthenticatorConfigById(authExecution.getAuthenticatorConfig()))\n+ .filter(Objects::nonNull)\n+ .map(authConfig -> {\n+ String levelAsStr = authConfig.getConfig().get(ConditionalLoaAuthenticator.LEVEL);\n+ try {\n+ // Check it can be cast to number\n+ return Integer.parseInt(levelAsStr);\n+ } catch (NullPointerException | NumberFormatException e) {\n+ logger.warnf(\"Invalid level '%s' configured for the configuration of LoA condition with alias '%s'. Level should be number.\", levelAsStr, authConfig.getAlias());\n+ return null;\n+ }\n+ })\n+ .filter(Objects::nonNull);\n+\n+ // Add 0 as a level used for SSO cookie\n+ return Stream.concat(Stream.of(Constants.MINIMUM_LOA), configuredLoas);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/OIDCWellKnownProvider.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/OIDCWellKnownProvider.java", "diff": "@@ -19,6 +19,7 @@ package org.keycloak.protocol.oidc;\nimport com.google.common.collect.Streams;\nimport org.keycloak.OAuth2Constants;\n+import org.keycloak.authentication.AuthenticatorUtil;\nimport org.keycloak.authentication.ClientAuthenticator;\nimport org.keycloak.authentication.ClientAuthenticatorFactory;\nimport org.keycloak.crypto.CekManagementProvider;\n@@ -28,6 +29,7 @@ import org.keycloak.crypto.SignatureProvider;\nimport org.keycloak.jose.jws.Algorithm;\nimport org.keycloak.models.CibaConfig;\nimport org.keycloak.models.ClientScopeModel;\n+import org.keycloak.models.Constants;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint;\n@@ -37,6 +39,7 @@ import org.keycloak.protocol.oidc.grants.device.endpoints.DeviceEndpoint;\nimport org.keycloak.protocol.oidc.par.endpoints.ParEndpoint;\nimport org.keycloak.protocol.oidc.representations.MTLSEndpointAliases;\nimport org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation;\n+import org.keycloak.protocol.oidc.utils.AcrUtils;\nimport org.keycloak.protocol.oidc.utils.OIDCResponseType;\nimport org.keycloak.provider.Provider;\nimport org.keycloak.provider.ProviderFactory;\n@@ -54,6 +57,7 @@ import javax.ws.rs.core.UriInfo;\nimport java.net.URI;\nimport java.util.AbstractMap;\n+import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\n@@ -145,6 +149,7 @@ public class OIDCWellKnownProvider implements WellKnownProvider {\nconfig.setSubjectTypesSupported(DEFAULT_SUBJECT_TYPES_SUPPORTED);\nconfig.setResponseModesSupported(DEFAULT_RESPONSE_MODES_SUPPORTED);\nconfig.setGrantTypesSupported(DEFAULT_GRANT_TYPES_SUPPORTED);\n+ config.setAcrValuesSupported(getAcrValuesSupported(realm));\nconfig.setTokenEndpointAuthMethodsSupported(getClientAuthMethodsSupported());\nconfig.setTokenEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false));\n@@ -253,6 +258,18 @@ public class OIDCWellKnownProvider implements WellKnownProvider {\nreturn getSupportedAlgorithms(ContentEncryptionProvider.class, false);\n}\n+ private List<String> getAcrValuesSupported(RealmModel realm) {\n+ // Values explicitly set on the realm mapping\n+ Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm);\n+ List<String> result = new ArrayList<>(realmAcrLoaMap.keySet());\n+\n+ // Add LoA levels configured in authentication flow in addition to the realm values\n+ result.addAll(AuthenticatorUtil.getLoAConfiguredInRealmBrowserFlow(realm)\n+ .map(String::valueOf)\n+ .collect(Collectors.toList()));\n+ return result;\n+ }\n+\nprivate List<String> getSupportedEncryptionAlgorithms() {\nreturn getSupportedAlgorithms(CekManagementProvider.class, false);\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/AcrUtils.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/AcrUtils.java", "diff": "@@ -28,6 +28,7 @@ import java.util.Map;\nimport org.jboss.logging.Logger;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.Constants;\n+import org.keycloak.models.RealmModel;\nimport org.keycloak.representations.ClaimsRepresentation;\nimport org.keycloak.representations.IDToken;\nimport org.keycloak.util.JsonSerialization;\n@@ -71,7 +72,22 @@ public class AcrUtils {\nreturn acrValues;\n}\n+ /**\n+ * @param client\n+ * @return map corresponding to \"acr-to-loa\" client attribute. It will fallback to realm in case \"acr-to-loa\" mapping not configured on client\n+ */\npublic static Map<String, Integer> getAcrLoaMap(ClientModel client) {\n+ Map<String, Integer> result = getAcrLoaMapForClientOnly(client);\n+ if (result.isEmpty()) {\n+ // Fallback to realm\n+ return getAcrLoaMap(client.getRealm());\n+ } else {\n+ return result;\n+ }\n+ }\n+\n+\n+ private static Map<String, Integer> getAcrLoaMapForClientOnly(ClientModel client) {\nString map = client.getAttribute(Constants.ACR_LOA_MAP);\nif (map == null || map.isEmpty()) {\nreturn Collections.emptyMap();\n@@ -79,7 +95,24 @@ public class AcrUtils {\ntry {\nreturn JsonSerialization.readValue(map, new TypeReference<Map<String, Integer>>() {});\n} catch (IOException e) {\n- LOGGER.warn(\"Invalid client configuration (ACR-LOA map)\");\n+ LOGGER.warnf(\"Invalid client configuration (ACR-LOA map) for client '%s'\", client.getClientId());\n+ return Collections.emptyMap();\n+ }\n+ }\n+\n+ /**\n+ * @param realm\n+ * @return map corresponding to \"acr-to-loa\" realm attribute.\n+ */\n+ public static Map<String, Integer> getAcrLoaMap(RealmModel realm) {\n+ String map = realm.getAttribute(Constants.ACR_LOA_MAP);\n+ if (map == null || map.isEmpty()) {\n+ return Collections.emptyMap();\n+ }\n+ try {\n+ return JsonSerialization.readValue(map, new TypeReference<Map<String, Integer>>() {});\n+ } catch (IOException e) {\n+ LOGGER.warn(\"Invalid realm configuration (ACR-LOA map)\");\nreturn Collections.emptyMap();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java", "diff": "@@ -29,6 +29,7 @@ import org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.authentication.authenticators.browser.PasswordFormFactory;\nimport org.keycloak.authentication.authenticators.browser.UsernameFormFactory;\nimport org.keycloak.authentication.authenticators.conditional.ConditionalLoaAuthenticator;\n@@ -38,12 +39,15 @@ import org.keycloak.models.AuthenticationExecutionModel.Requirement;\nimport org.keycloak.models.Constants;\nimport org.keycloak.representations.ClaimsRepresentation;\nimport org.keycloak.representations.IDToken;\n+import org.keycloak.representations.idm.ClientRepresentation;\nimport org.keycloak.representations.idm.EventRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.testsuite.AbstractTestRealmKeycloakTest;\nimport org.keycloak.testsuite.AssertEvents;\n+import org.keycloak.testsuite.admin.ApiUtil;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\nimport org.keycloak.testsuite.authentication.PushButtonAuthenticatorFactory;\n+import org.keycloak.testsuite.client.KeycloakTestingClient;\nimport org.keycloak.testsuite.pages.ErrorPage;\nimport org.keycloak.testsuite.pages.LoginUsernameOnlyPage;\nimport org.keycloak.testsuite.pages.PasswordPage;\n@@ -81,18 +85,26 @@ public class LevelOfAssuranceFlowTest extends AbstractTestRealmKeycloakTest {\n@Override\npublic void configureTestRealm(RealmRepresentation testRealm) {\ntry {\n+ findTestApp(testRealm).setAttributes(Collections.singletonMap(Constants.ACR_LOA_MAP, getAcrToLoaMappingForClient()));\n+ } catch (IOException e) {\n+ throw new RuntimeException(e);\n+ }\n+ }\n+\n+ private String getAcrToLoaMappingForClient() throws IOException {\nMap<String, Integer> acrLoaMap = new HashMap<>();\nacrLoaMap.put(\"copper\", 0);\nacrLoaMap.put(\"silver\", 1);\nacrLoaMap.put(\"gold\", 2);\n- findTestApp(testRealm).setAttributes(Collections.singletonMap(Constants.ACR_LOA_MAP, JsonSerialization.writeValueAsString(acrLoaMap)));\n- } catch (IOException e) {\n- throw new RuntimeException(e);\n- }\n+ return JsonSerialization.writeValueAsString(acrLoaMap);\n}\n@Before\npublic void setupFlow() {\n+ configureStepUpFlow(testingClient);\n+ }\n+\n+ public static void configureStepUpFlow(KeycloakTestingClient testingClient) {\nfinal String newFlowAlias = \"browser - Level of Authentication FLow\";\ntestingClient.server(TEST_REALM_NAME).run(session -> FlowUtil.inCurrentRealm(session).copyBrowserFlow(newFlowAlias));\ntestingClient.server(TEST_REALM_NAME)\n@@ -286,6 +298,45 @@ public class LevelOfAssuranceFlowTest extends AbstractTestRealmKeycloakTest {\nassertLoggedInWithAcr(\"gold\");\n}\n+\n+ @Test\n+ public void testRealmAcrLoaMapping() throws IOException {\n+ // Setup realm acr-to-loa mapping\n+ RealmRepresentation realmRep = testRealm().toRepresentation();\n+ Map<String, Integer> acrLoaMap = new HashMap<>();\n+ acrLoaMap.put(\"realm:copper\", 0);\n+ acrLoaMap.put(\"realm:silver\", 1);\n+ acrLoaMap.put(\"realm:gold\", 2);\n+ realmRep.getAttributes().put(Constants.ACR_LOA_MAP, JsonSerialization.writeValueAsString(acrLoaMap));\n+ testRealm().update(realmRep);\n+\n+ // Remove acr-to-loa mapping from the client. It should use realm acr-to-loa mapping\n+ ClientResource testClient = ApiUtil.findClientByClientId(testRealm(), \"test-app\");\n+ ClientRepresentation testClientRep = testClient.toRepresentation();\n+ testClientRep.getAttributes().put(Constants.ACR_LOA_MAP, \"{}\");\n+ testClient.update(testClientRep);\n+\n+ openLoginFormWithAcrClaim(true, \"realm:gold\");\n+ authenticateWithUsername();\n+ authenticateWithPassword();\n+ assertLoggedInWithAcr(\"realm:gold\");\n+\n+ // Add \"acr-to-loa\" back to the client. Client mapping will be used instead of realm mapping\n+ testClientRep.getAttributes().put(Constants.ACR_LOA_MAP, getAcrToLoaMappingForClient());\n+ testClient.update(testClientRep);\n+\n+ openLoginFormWithAcrClaim(true, \"realm:gold\");\n+ assertErrorPage(\"Invalid parameter: claims\");\n+\n+ openLoginFormWithAcrClaim(true, \"gold\");\n+ authenticateWithPassword();\n+ assertLoggedInWithAcr(\"gold\");\n+\n+ // Rollback\n+ realmRep.getAttributes().remove(Constants.ACR_LOA_MAP);\n+ testRealm().update(realmRep);\n+ }\n+\npublic void openLoginFormWithAcrClaim(boolean essential, String... acrValues) {\nopenLoginFormWithAcrClaim(oauth, essential, acrValues);\n}\n@@ -326,5 +377,6 @@ public class LevelOfAssuranceFlowTest extends AbstractTestRealmKeycloakTest {\nprivate void assertErrorPage(String expectedError) {\nAssert.assertThat(true, is(errorPage.isCurrent()));\nAssert.assertEquals(expectedError, errorPage.getError());\n+ events.clear();\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCWellKnownProviderTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCWellKnownProviderTest.java", "diff": "@@ -24,10 +24,12 @@ import org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.keycloak.OAuth2Constants;\n+import org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.broker.provider.util.SimpleHttp;\nimport org.keycloak.crypto.Algorithm;\nimport org.keycloak.jose.jwe.JWEConstants;\nimport org.keycloak.jose.jwk.JSONWebKeySet;\n+import org.keycloak.models.Constants;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocolService;\nimport org.keycloak.protocol.oidc.OIDCWellKnownProviderFactory;\n@@ -44,6 +46,8 @@ import org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.admin.AbstractAdminTest;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.forms.BrowserFlowTest;\n+import org.keycloak.testsuite.forms.LevelOfAssuranceFlowTest;\nimport org.keycloak.testsuite.util.AdminClientUtil;\nimport org.keycloak.testsuite.util.ClientManager;\nimport org.keycloak.testsuite.util.OAuthClient;\n@@ -58,6 +62,7 @@ import javax.ws.rs.core.Response;\nimport javax.ws.rs.core.UriBuilder;\nimport java.io.IOException;\nimport java.net.URI;\n+import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n@@ -296,6 +301,57 @@ public class OIDCWellKnownProviderTest extends AbstractKeycloakTest {\n}\n}\n+ @Test\n+ @AuthServerContainerExclude(REMOTE)\n+ public void testAcrValuesSupported() throws IOException {\n+ Client client = AdminClientUtil.createResteasyClient();\n+ try {\n+ // Default values when no \"acr-to-loa\" mapping and no authentication flow configured\n+ OIDCConfigurationRepresentation oidcConfig = getOIDCDiscoveryRepresentation(client, OAuthClient.AUTH_SERVER_ROOT);\n+ Assert.assertNames(oidcConfig.getAcrValuesSupported(), \"0\", \"1\");\n+\n+ // Update authentication flow and see it uses \"acr\" values from it\n+ LevelOfAssuranceFlowTest.configureStepUpFlow(testingClient);\n+ oidcConfig = getOIDCDiscoveryRepresentation(client, OAuthClient.AUTH_SERVER_ROOT);\n+ Assert.assertNames(oidcConfig.getAcrValuesSupported(), \"0\", \"1\", \"2\", \"3\");\n+\n+ // Configure \"ACR-To-Loa\" mapping and check it has both configured values and numbers from authentication flow\n+ RealmResource testRealm = adminClient.realm(\"test\");\n+ RealmRepresentation realmRep = testRealm.toRepresentation();\n+ Map<String, Integer> acrToLoa = new HashMap<>();\n+ acrToLoa.put(\"poor\", 0);\n+ acrToLoa.put(\"silver\", 1);\n+ acrToLoa.put(\"gold\", 2);\n+ String acrToLoaAttr = JsonSerialization.writeValueAsString(acrToLoa);\n+ realmRep.getAttributes().put(Constants.ACR_LOA_MAP, acrToLoaAttr);\n+ testRealm.update(realmRep);\n+\n+ oidcConfig = getOIDCDiscoveryRepresentation(client, OAuthClient.AUTH_SERVER_ROOT);\n+ Assert.assertNames(oidcConfig.getAcrValuesSupported(), \"poor\", \"silver\", \"gold\", \"0\", \"1\", \"2\", \"3\");\n+\n+ // Use mappings even with values not included in the authentication flow\n+ acrToLoa = new HashMap<>();\n+ acrToLoa.put(\"poor\", 0);\n+ acrToLoa.put(\"silver\", 1);\n+ acrToLoa.put(\"gold\", 2);\n+ acrToLoa.put(\"platinum\", 3);\n+ acrToLoa.put(\"diamond\", 4);\n+ acrToLoaAttr = JsonSerialization.writeValueAsString(acrToLoa);\n+ realmRep.getAttributes().put(Constants.ACR_LOA_MAP, acrToLoaAttr);\n+ testRealm.update(realmRep);\n+\n+ oidcConfig = getOIDCDiscoveryRepresentation(client, OAuthClient.AUTH_SERVER_ROOT);\n+ Assert.assertNames(oidcConfig.getAcrValuesSupported(), \"poor\", \"silver\", \"gold\", \"platinum\", \"diamond\", \"0\", \"1\", \"2\", \"3\");\n+\n+ // Revert realm and flow\n+ realmRep.getAttributes().remove(Constants.ACR_LOA_MAP);\n+ testRealm.update(realmRep);\n+ BrowserFlowTest.revertFlows(testRealm, \"browser - Level of Authentication FLow\");\n+ } finally {\n+ client.close();\n+ }\n+ }\n+\n@Test\n@AuthServerContainerExclude(REMOTE)\npublic void testDefaultProviderCustomizations() throws IOException {\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/messages/admin-messages_en.properties", "new_path": "themes/src/main/resources/theme/base/admin/messages/admin-messages_en.properties", "diff": "@@ -1941,7 +1941,8 @@ use-idtoken-as-detached-signature=Use ID Token as a Detached Signature\nuse-idtoken-as-detached-signature.tooltip=This makes ID token returned from Authorization Endpoint in OIDC Hybrid flow use as a detached signature defined in FAPI 1.0 Advanced Security Profile. Therefore, this ID token does not include an authenticated user's information.\nacr-loa-map=ACR to LoA Mapping\n-acr-loa-map.tooltip=Define which ACR (Authentication Context Class Reference) value is mapped to which LoA (Level of Authentication). The ACR can be any value, whereas the LoA must be numeric.\n+acr-loa-map.tooltip=Define which ACR (Authentication Context Class Reference) value is mapped to which LoA (Level of Authentication). The ACR can be any value, whereas the LoA must be numeric. The LoA typically refers to the numbers configured as levels in the conditions in the authentication flow. The ACR refers to the value used in the OIDC/SAML authorization request and returned to client in the tokens.\n+acr-loa-map-client.tooltip=Define which ACR (Authentication Context Class Reference) value is mapped to which LoA (Level of Authentication). The ACR can be any value, whereas the LoA must be numeric. This is recommended to be configured at the realm level where it is shared for all the clients. If you configure at the client level, the client mapping will take precedence over the mapping from the realm level.\nkey-not-allowed-here=Key '{{character}}' is not allowed here.\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js", "new_path": "themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js", "diff": "@@ -361,7 +361,7 @@ module.controller('RealmDetailCtrl', function($scope, Current, Realm, realm, ser\n};\n});\n-function genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $route, Dialog, Notifications, url) {\n+function genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $route, Dialog, Notifications, url, saveCallback, resetCallback) {\n$scope.realm = angular.copy(realm);\n$scope.serverInfo = serverInfo;\n$scope.registrationAllowed = $scope.realm.registrationAllowed;\n@@ -377,6 +377,9 @@ function genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $r\n}, true);\n$scope.save = function() {\n+ if (saveCallback) {\n+ saveCallback();\n+ }\nvar realmCopy = angular.copy($scope.realm);\nconsole.log('updating realm...');\n$scope.changed = false;\n@@ -390,6 +393,9 @@ function genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $r\n$scope.reset = function() {\n$scope.realm = angular.copy(oldCopy);\n+ if (resetCallback) {\n+ resetCallback();\n+ }\n$scope.changed = false;\n};\n@@ -411,7 +417,53 @@ module.controller('RealmLoginSettingsCtrl', function($scope, Current, Realm, rea\n}\n});\n- genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $route, Dialog, Notifications, \"/realms/\" + realm.realm + \"/login-settings\");\n+ var resetCallback = function() {\n+ try {\n+ $scope.acrLoaMap = JSON.parse(realm.attributes[\"acr.loa.map\"] || \"{}\");\n+ } catch (e) {\n+ $scope.acrLoaMap = {};\n+ }\n+ }\n+ resetCallback();\n+ var previousNewAcr = undefined;\n+ var previousNewLoa = undefined;\n+\n+ $scope.$watch('newAcr', function() {\n+ var changed = $scope.newAcr != previousNewAcr;\n+ if (changed) {\n+ previousNewAcr = $scope.newAcr;\n+ $scope.changed = true;\n+ }\n+ }, true);\n+ $scope.$watch('newLoa', function() {\n+ var changed = $scope.newLoa != previousNewLoa;\n+ if (changed) {\n+ previousNewLoa = $scope.newLoa;\n+ $scope.changed = true;\n+ }\n+ }, true);\n+ $scope.deleteAcrLoaMapping = function(acr) {\n+ delete $scope.acrLoaMap[acr];\n+ $scope.changed = true;\n+ updateRealmAcrAttribute();\n+ }\n+ $scope.checkAddAcrLoaMapping = function() {\n+ if ($scope.newAcr && $scope.newAcr.length > 0 && $scope.newLoa && $scope.newLoa.length > 0 && $scope.newLoa.match(/^[0-9]+$/)) {\n+ console.log(\"Adding acrLoaMapping: \" + $scope.newLoa + \" : \" + $scope.newAcr);\n+ $scope.acrLoaMap[$scope.newAcr] = $scope.newLoa;\n+ $scope.newAcr = $scope.newLoa = \"\";\n+ $scope.changed = true;\n+ updateRealmAcrAttribute();\n+ }\n+ }\n+\n+ function updateRealmAcrAttribute() {\n+ var acrLoaMapStr = JSON.stringify($scope.acrLoaMap);\n+ console.log(\"Updating realm acr.loa.map attribute: \" + acrLoaMapStr);\n+ $scope.realm.attributes[\"acr.loa.map\"] = acrLoaMapStr;\n+ }\n+\n+ genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $route, Dialog, Notifications, \"/realms/\" + realm.realm + \"/login-settings\", $scope.checkAddAcrLoaMapping, resetCallback);\n});\nmodule.controller('RealmOtpPolicyCtrl', function($scope, Current, Realm, realm, serverInfo, $http, $route, Dialog, Notifications) {\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/client-detail.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/client-detail.html", "diff": "</div>\n</div>\n</div>\n- <kc-tooltip>{{:: 'acr-loa-map.tooltip' | translate}}</kc-tooltip>\n+ <kc-tooltip>{{:: 'acr-loa-map-client.tooltip' | translate}}</kc-tooltip>\n</div>\n</fieldset>\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/realm-login-settings.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/realm-login-settings.html", "diff": "</div>\n<kc-tooltip>{{:: 'sslRequired.tooltip' | translate}}</kc-tooltip>\n</div>\n+ <div class=\"form-group clearfix block\">\n+ <label class=\"col-md-2 control-label\" for=\"newAcr\">{{:: 'acr-loa-map' | translate}}</label>\n+ <div class=\"col-sm-6\">\n+ <div class=\"input-group input-map\" ng-repeat=\"(acr, loa) in acrLoaMap\">\n+ <input class=\"form-control\" readonly value=\"{{acr}}\">\n+ <input class=\"form-control\" ng-model=\"acrLoaMap[acr]\">\n+ <div class=\"input-group-btn\">\n+ <button class=\"btn btn-default\" type=\"button\" data-ng-click=\"deleteAcrLoaMapping(acr)\"><span class=\"fa fa-minus\"></span></button>\n+ </div>\n+ </div>\n+ <div class=\"input-group input-map\">\n+ <input class=\"form-control\" ng-model=\"newAcr\" id=\"newAcr\" placeholder=\"ACR\">\n+ <input class=\"form-control\" ng-model=\"newLoa\" id=\"newLoa\" placeholder=\"LOA\">\n+ <div class=\"input-group-btn\">\n+ <button class=\"btn btn-default\" type=\"button\" data-ng-click=\"checkAddAcrLoaMapping()\"><span class=\"fa fa-plus\"></span></button>\n+ </div>\n+ </div>\n+ </div>\n+ <kc-tooltip>{{:: 'acr-loa-map.tooltip' | translate}}</kc-tooltip>\n+ </div>\n</fieldset>\n<div class=\"form-group\" data-ng-show=\"access.manageRealm\">\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Support for acr_values_supported in OIDC well-known endpoint (#10265) * Support for acr_values_supported in OIDC well-known endpoint closes #10159
339,666
09.11.2021 11:30:37
-3,600
febb447919044943241ad97200821c7da5099cb3
Use real 'external' client object id to store AuthenticatedClientSession in UserSession object, so that the client session can be looked by the client object id in further requests.
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/JpaUserSessionPersisterProvider.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/session/JpaUserSessionPersisterProvider.java", "diff": "@@ -413,7 +413,12 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv\nreturn false;\n}\n- userSession.getAuthenticatedClientSessions().put(clientSessionEntity.getClientId(), clientSessAdapter);\n+ String clientId = clientSessionEntity.getClientId();\n+ if (isExternalClient(clientSessionEntity)) {\n+ clientId = getExternalClientId(clientSessionEntity);\n+ }\n+\n+ userSession.getAuthenticatedClientSessions().put(clientId, clientSessAdapter);\nreturn true;\n}\n@@ -439,8 +444,8 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv\nprivate PersistentAuthenticatedClientSessionAdapter toAdapter(RealmModel realm, PersistentUserSessionAdapter userSession, PersistentClientSessionEntity entity) {\nString clientId = entity.getClientId();\n- if (!entity.getExternalClientId().equals(\"local\")) {\n- clientId = new StorageId(entity.getClientStorageProvider(), entity.getExternalClientId()).getId();\n+ if (isExternalClient(entity)) {\n+ clientId = getExternalClientId(entity);\n}\nClientModel client = realm.getClientById(clientId);\n@@ -497,4 +502,12 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv\nprivate boolean offlineFromString(String offlineStr) {\nreturn \"1\".equals(offlineStr);\n}\n+\n+ private boolean isExternalClient(PersistentClientSessionEntity entity) {\n+ return !entity.getExternalClientId().equals(PersistentClientSessionEntity.LOCAL);\n+ }\n+\n+ private String getExternalClientId(PersistentClientSessionEntity entity) {\n+ return new StorageId(entity.getClientStorageProvider(), entity.getExternalClientId()).getId();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/pom.xml", "new_path": "testsuite/model/pom.xml", "diff": "</properties>\n</profile>\n+ <profile>\n+ <id>jpa+infinispan+client-storage</id>\n+ <properties>\n+ <keycloak.model.parameters>Jpa,Infinispan,HardcodedClientStorage</keycloak.model.parameters>\n+ </properties>\n+ </profile>\n+\n<profile>\n<id>jpa+cross-dc-infinispan</id>\n<properties>\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/parameters/HardcodedClientStorage.java", "diff": "+/*\n+ * Copyright 2020 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.keycloak.testsuite.model.parameters;\n+\n+import com.google.common.collect.ImmutableSet;\n+import org.keycloak.provider.ProviderFactory;\n+import org.keycloak.provider.Spi;\n+import org.keycloak.storage.client.ClientStorageProviderModel;\n+import org.keycloak.storage.client.ClientStorageProviderSpi;\n+import org.keycloak.testsuite.federation.HardcodedClientStorageProviderFactory;\n+import org.keycloak.testsuite.model.Config;\n+import org.keycloak.testsuite.model.KeycloakModelParameters;\n+\n+import java.util.Set;\n+import java.util.concurrent.atomic.AtomicInteger;\n+import java.util.stream.Stream;\n+\n+public class HardcodedClientStorage extends KeycloakModelParameters {\n+ static final Set<Class<? extends Spi>> ALLOWED_SPIS = ImmutableSet.<Class<? extends Spi>>builder()\n+ .add(ClientStorageProviderSpi.class)\n+ .build();\n+\n+ static final Set<Class<? extends ProviderFactory>> ALLOWED_FACTORIES = ImmutableSet.<Class<? extends ProviderFactory>>builder()\n+ .add(HardcodedClientStorageProviderFactory.class)\n+ .build();\n+\n+ private final AtomicInteger counter = new AtomicInteger();\n+\n+ @Override\n+ public void updateConfig(Config cf) {\n+ cf.spi(\"client-storage\").defaultProvider(HardcodedClientStorageProviderFactory.PROVIDER_ID);\n+ }\n+\n+ @Override\n+ public <T> Stream<T> getParameters(Class<T> clazz) {\n+ if (ClientStorageProviderModel.class.isAssignableFrom(clazz)) {\n+ ClientStorageProviderModel clientStorage = new ClientStorageProviderModel();\n+ clientStorage.setName(HardcodedClientStorageProviderFactory.PROVIDER_ID + \":\" + counter.getAndIncrement());\n+ clientStorage.setProviderId(HardcodedClientStorageProviderFactory.PROVIDER_ID);\n+ return Stream.of((T) clientStorage);\n+ } else {\n+ return super.getParameters(clazz);\n+ }\n+ }\n+\n+\n+ public HardcodedClientStorage() {\n+ super(ALLOWED_SPIS, ALLOWED_FACTORIES);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionPersisterProviderTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionPersisterProviderTest.java", "diff": "@@ -19,6 +19,7 @@ package org.keycloak.testsuite.model.session;\nimport org.junit.Assert;\nimport org.junit.Test;\n+import org.keycloak.OAuth2Constants;\nimport org.keycloak.common.util.Time;\nimport org.keycloak.models.AuthenticatedClientSessionModel;\nimport org.keycloak.models.ClientModel;\n@@ -33,6 +34,7 @@ import org.keycloak.models.UserSessionProvider;\nimport org.keycloak.models.session.UserSessionPersisterProvider;\nimport org.keycloak.models.utils.ResetTimeOffsetEvent;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\n+import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;\nimport org.keycloak.services.managers.ClientManager;\nimport org.keycloak.services.managers.RealmManager;\n@@ -53,6 +55,9 @@ import static org.hamcrest.MatcherAssert.assertThat;\nimport org.keycloak.models.Constants;\nimport org.keycloak.models.sessions.infinispan.InfinispanUserSessionProviderFactory;\nimport org.hamcrest.Matchers;\n+import org.keycloak.storage.client.ClientStorageProvider;\n+import org.keycloak.storage.client.ClientStorageProviderModel;\n+import org.keycloak.testsuite.federation.HardcodedClientStorageProviderFactory;\nimport org.keycloak.testsuite.model.KeycloakModelTest;\nimport org.keycloak.testsuite.model.RequireProvider;\nimport java.util.LinkedList;\n@@ -508,6 +513,68 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {\n});\n}\n+ @Test\n+ @RequireProvider(ClientStorageProvider.class)\n+ public void testPersistenceWithLoadWithExternalClientStorage() {\n+ try {\n+ inComittedTransaction(session -> {\n+ setupClientStorageComponents(session, session.realms().getRealm(realmId));\n+ });\n+\n+ int started = Time.currentTime();\n+\n+ UserSessionModel origSession = inComittedTransaction(session -> {\n+ // Create session in infinispan\n+ RealmModel realm = session.realms().getRealm(realmId);\n+\n+ UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, \"user1\"), \"user1\", \"127.0.0.1\", \"form\", true, null, null);\n+ createClientSession(session, realmId, realm.getClientByClientId(\"test-app\"), userSession, \"http://redirect\", \"state\");\n+ createClientSession(session, realmId, realm.getClientByClientId(\"external-storage-client\"), userSession, \"http://redirect\", \"state\");\n+\n+ return userSession;\n+ });\n+\n+ inComittedTransaction(session -> {\n+ // Persist created userSession and clientSessions as offline\n+ persistUserSession(session, origSession, true);\n+ });\n+\n+ inComittedTransaction(session -> {\n+ // Assert offline session\n+ RealmModel realm = session.realms().getRealm(realmId);\n+ List<UserSessionModel> loadedSessions = loadPersistedSessionsPaginated(session, true, 1, 1, 1);\n+\n+ assertSessions(loadedSessions, new String[]{origSession.getId()});\n+ assertSessionLoaded(loadedSessions, origSession.getId(), session.users().getUserByUsername(realm, \"user1\"), \"127.0.0.1\", started, started, \"test-app\", \"external-storage-client\");\n+ });\n+ } finally {\n+ inComittedTransaction(session -> {\n+ cleanClientStorageComponents(session, session.realms().getRealm(realmId));\n+ });\n+ }\n+ }\n+\n+ private void setupClientStorageComponents(KeycloakSession s, RealmModel realm) {\n+ getParameters(ClientStorageProviderModel.class).forEach(cm -> {\n+ cm.put(HardcodedClientStorageProviderFactory.CLIENT_ID, \"external-storage-client\");\n+ cm.put(HardcodedClientStorageProviderFactory.DELAYED_SEARCH, Boolean.toString(false));\n+ realm.addComponentModel(cm);\n+ });\n+\n+ // Required by HardcodedClientStorageProvider\n+ s.roles().addRealmRole(realm, OAuth2Constants.OFFLINE_ACCESS);\n+ s.clientScopes().addClientScope(realm, OAuth2Constants.OFFLINE_ACCESS);\n+ s.clientScopes().addClientScope(realm, OIDCLoginProtocolFactory.ROLES_SCOPE);\n+ s.clientScopes().addClientScope(realm, OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE);\n+ }\n+\n+ private void cleanClientStorageComponents(KeycloakSession s, RealmModel realm) {\n+ s.roles().removeRoles(realm);\n+ s.clientScopes().removeClientScopes(realm);\n+\n+ realm.removeComponents(realm.getId());\n+ }\n+\nprotected static AuthenticatedClientSessionModel createClientSession(KeycloakSession session, String realmId, ClientModel client, UserSessionModel userSession, String redirect, String state) {\nRealmModel realm = session.realms().getRealm(realmId);\nAuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, client, userSession);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-19297 Use real 'external' client object id to store AuthenticatedClientSession in UserSession object, so that the client session can be looked by the client object id in further requests.
339,465
22.02.2022 07:54:30
-3,600
8c3fc5a60e0e0fbff7b0d8ed36b887812532936e
Option for client to specify default acr level Closes
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/models/Constants.java", "new_path": "server-spi-private/src/main/java/org/keycloak/models/Constants.java", "diff": "@@ -135,6 +135,7 @@ public final class Constants {\npublic static final String REQUESTED_LEVEL_OF_AUTHENTICATION = \"requested-level-of-authentication\";\npublic static final String FORCE_LEVEL_OF_AUTHENTICATION = \"force-level-of-authentication\";\npublic static final String ACR_LOA_MAP = \"acr.loa.map\";\n+ public static final String DEFAULT_ACR_VALUES = \"default.acr.values\";\npublic static final int MINIMUM_LOA = 0;\npublic static final int NO_LOA = -1;\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/OIDCAdvancedConfigWrapper.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/OIDCAdvancedConfigWrapper.java", "diff": "@@ -375,13 +375,13 @@ public class OIDCAdvancedConfigWrapper {\n}\n}\n- private List<String> getAttributeMultivalued(String attrKey) {\n+ public List<String> getAttributeMultivalued(String attrKey) {\nString attrValue = getAttribute(attrKey);\nif (attrValue == null) return Collections.emptyList();\nreturn Arrays.asList(Constants.CFG_DELIMITER_PATTERN.split(attrValue));\n}\n- private void setAttributeMultivalued(String attrKey, List<String> attrValues) {\n+ public void setAttributeMultivalued(String attrKey, List<String> attrValues) {\nif (attrValues == null || attrValues.size() == 0) {\n// Remove attribute\nsetAttribute(attrKey, null);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "diff": "@@ -903,7 +903,7 @@ public class TokenManager {\nif (acr == null) {\nacr = AcrUtils.mapLoaToAcr(loa, acrLoaMap, AcrUtils.getAcrValues(\nclientSession.getNote(OIDCLoginProtocol.CLAIMS_PARAM),\n- clientSession.getNote(OIDCLoginProtocol.ACR_PARAM)));\n+ clientSession.getNote(OIDCLoginProtocol.ACR_PARAM), clientSession.getClient()));\nif (acr == null) {\nacr = AcrUtils.mapLoaToAcr(loa, acrLoaMap, acrLoaMap.keySet());\nif (acr == null) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java", "diff": "@@ -296,7 +296,7 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {\nList<String> acrValues = AcrUtils.getRequiredAcrValues(request.getClaims());\nif (acrValues.isEmpty()) {\n- acrValues = AcrUtils.getAcrValues(request.getClaims(), request.getAcr());\n+ acrValues = AcrUtils.getAcrValues(request.getClaims(), request.getAcr(), authenticationSession.getClient());\n} else {\nauthenticationSession.setClientNote(Constants.FORCE_LEVEL_OF_AUTHENTICATION, \"true\");\n}\n@@ -309,11 +309,11 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {\n// this is an unknown acr. In case of an essential claim, we directly reject authentication as we cannot met the specification requirement. Otherwise fallback to minimum LoA\nboolean essential = Boolean.parseBoolean(authenticationSession.getClientNote(Constants.FORCE_LEVEL_OF_AUTHENTICATION));\nif (essential) {\n- logger.errorf(\"Requested essential acr value '%s' is not a number and it is not mapped in the client mappings. Please doublecheck your client configuration or correct ACR passed in the 'claims' parameter.\", acr);\n+ logger.errorf(\"Requested essential acr value '%s' is not a number and it is not mapped in the ACR-To-Loa mappings of realm or client. Please doublecheck ACR-to-LOA mapping or correct ACR passed in the 'claims' parameter.\", acr);\nevent.error(Errors.INVALID_REQUEST);\nthrow new ErrorPageException(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.INVALID_PARAMETER, OIDCLoginProtocol.CLAIMS_PARAM);\n} else {\n- logger.warnf(\"Requested acr value '%s' is not a number and it is not mapped in the client mappings. Please doublecheck your client configuration or correct ACR passed in the 'claims' parameter. Ignoring passed acr\", acr);\n+ logger.warnf(\"Requested acr value '%s' is not a number and it is not mapped in the ACR-To-Loa mappings of realm or client. Please doublecheck ACR-to-LOA mapping or correct used ACR.\", acr);\nreturn Constants.MINIMUM_LOA;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/AcrUtils.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/AcrUtils.java", "diff": "@@ -29,6 +29,7 @@ import org.jboss.logging.Logger;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.Constants;\nimport org.keycloak.models.RealmModel;\n+import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\nimport org.keycloak.representations.ClaimsRepresentation;\nimport org.keycloak.representations.IDToken;\nimport org.keycloak.util.JsonSerialization;\n@@ -41,8 +42,14 @@ public class AcrUtils {\nreturn getAcrValues(claimsParam, null, true);\n}\n- public static List<String> getAcrValues(String claimsParam, String acrValuesParam) {\n- return getAcrValues(claimsParam, acrValuesParam, false);\n+ public static List<String> getAcrValues(String claimsParam, String acrValuesParam, ClientModel client) {\n+ List<String> fromParams = getAcrValues(claimsParam, acrValuesParam, false);\n+ if (!fromParams.isEmpty()) {\n+ return fromParams;\n+ }\n+\n+ // Fallback to default ACR values of client (if configured)\n+ return getDefaultAcrValues(client);\n}\nprivate static List<String> getAcrValues(String claimsParam, String acrValuesParam, boolean essential) {\n@@ -140,4 +147,9 @@ public class AcrUtils {\n}\nreturn acr;\n}\n+\n+\n+ public static List<String> getDefaultAcrValues(ClientModel client) {\n+ return OIDCAdvancedConfigWrapper.fromClientModel(client).getAttributeMultivalued(Constants.DEFAULT_ACR_VALUES);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/clientregistration/oidc/DescriptionConverter.java", "new_path": "services/src/main/java/org/keycloak/services/clientregistration/oidc/DescriptionConverter.java", "diff": "@@ -28,12 +28,14 @@ import org.keycloak.jose.jwk.JWK;\nimport org.keycloak.jose.jwk.JWKParser;\nimport org.keycloak.jose.jws.Algorithm;\nimport org.keycloak.models.CibaConfig;\n+import org.keycloak.models.Constants;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.ParConfig;\nimport org.keycloak.models.utils.KeycloakModelUtils;\nimport org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.protocol.oidc.mappers.PairwiseSubMapperHelper;\n+import org.keycloak.protocol.oidc.utils.AcrUtils;\nimport org.keycloak.protocol.oidc.utils.AuthorizeClientUtil;\nimport org.keycloak.protocol.oidc.utils.OIDCResponseType;\nimport org.keycloak.protocol.oidc.utils.PairwiseSubMapperUtils;\n@@ -234,6 +236,10 @@ public class DescriptionConverter {\nconfigWrapper.setFrontChannelLogoutUrl(Optional.ofNullable(clientOIDC.getFrontChannelLogoutUri()).orElse(null));\n+ if (clientOIDC.getDefaultAcrValues() != null) {\n+ configWrapper.setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, clientOIDC.getDefaultAcrValues());\n+ }\n+\nreturn client;\n}\n@@ -414,6 +420,11 @@ public class DescriptionConverter {\nresponse.setFrontChannelLogoutUri(config.getFrontChannelLogoutUrl());\n+ List<String> defaultAcrValues = config.getAttributeMultivalued(Constants.DEFAULT_ACR_VALUES);\n+ if (!defaultAcrValues.isEmpty()) {\n+ response.setDefaultAcrValues(defaultAcrValues);\n+ }\n+\nreturn response;\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/validation/DefaultClientValidationProvider.java", "new_path": "services/src/main/java/org/keycloak/validation/DefaultClientValidationProvider.java", "diff": "*/\npackage org.keycloak.validation;\n+import org.keycloak.authentication.AuthenticatorUtil;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.ClientScopeModel;\nimport org.keycloak.protocol.ProtocolMapperConfigException;\n@@ -23,6 +24,7 @@ import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\nimport org.keycloak.protocol.oidc.OIDCConfigAttributes;\nimport org.keycloak.protocol.oidc.grants.ciba.CibaClientValidation;\nimport org.keycloak.protocol.oidc.mappers.PairwiseSubMapperHelper;\n+import org.keycloak.protocol.oidc.utils.AcrUtils;\nimport org.keycloak.protocol.oidc.utils.PairwiseSubMapperUtils;\nimport org.keycloak.protocol.oidc.utils.PairwiseSubMapperValidator;\nimport org.keycloak.protocol.oidc.utils.SubjectType;\n@@ -35,6 +37,7 @@ import java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.List;\n+import java.util.Map;\nimport java.util.Set;\nimport static org.keycloak.models.utils.ModelToRepresentation.toRepresentation;\n@@ -133,6 +136,7 @@ public class DefaultClientValidationProvider implements ClientValidationProvider\nvalidatePairwiseInClientModel(context);\nnew CibaClientValidation(context).validate();\nvalidateJwks(context);\n+ validateDefaultAcrValues(context);\nreturn context.toResult();\n}\n@@ -142,6 +146,7 @@ public class DefaultClientValidationProvider implements ClientValidationProvider\nvalidateUrls(context);\nvalidatePairwiseInOIDCClient(context);\nnew CibaClientValidation(context).validate();\n+ validateDefaultAcrValues(context);\nreturn context.toResult();\n}\n@@ -264,4 +269,20 @@ public class DefaultClientValidationProvider implements ClientValidationProvider\ncontext.addError(\"jwksUrl\", \"Illegal to use both jwks_uri and jwks_string\", \"duplicatedJwksSettings\");\n}\n}\n+\n+ private void validateDefaultAcrValues(ValidationContext<ClientModel> context) {\n+ ClientModel client = context.getObjectToValidate();\n+ List<String> defaultAcrValues = AcrUtils.getDefaultAcrValues(client);\n+ Map<String, Integer> acrToLoaMap = AcrUtils.getAcrLoaMap(client);\n+ if (acrToLoaMap.isEmpty()) {\n+ acrToLoaMap = AcrUtils.getAcrLoaMap(client.getRealm());\n+ }\n+ for (String configuredAcr : defaultAcrValues) {\n+ if (acrToLoaMap.containsKey(configuredAcr)) continue;\n+ if (!AuthenticatorUtil.getLoAConfiguredInRealmBrowserFlow(client.getRealm())\n+ .anyMatch(level -> configuredAcr.equals(String.valueOf(level)))) {\n+ context.addError(\"defaultAcrValues\", \"Default ACR values need to contain values specified in the ACR-To-Loa mapping or number levels from set realm browser flow\");\n+ }\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java", "diff": "@@ -32,6 +32,7 @@ import org.keycloak.events.Errors;\nimport org.keycloak.jose.jwe.JWEConstants;\nimport org.keycloak.jose.jws.Algorithm;\nimport org.keycloak.models.CibaConfig;\n+import org.keycloak.models.Constants;\nimport org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.protocol.oidc.utils.OIDCResponseType;\n@@ -44,6 +45,7 @@ import org.keycloak.representations.oidc.OIDCClientRepresentation;\nimport org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.admin.ApiUtil;\nimport org.keycloak.testsuite.util.KeycloakModelUtils;\n+import org.keycloak.util.JsonSerialization;\nimport java.util.*;\nimport java.util.stream.Collectors;\n@@ -729,4 +731,38 @@ public class OIDCClientRegistrationTest extends AbstractClientRegistrationTest {\nOIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient);\nAssert.assertTrue(config.isUseRefreshToken());\n}\n+\n+ @Test\n+ public void testDefaultAcrValues() throws Exception {\n+ // Set realm acr-to-loa mapping\n+ RealmRepresentation realmRep = adminClient.realm(\"test\").toRepresentation();\n+ Map<String, Integer> acrLoaMap = new HashMap<>();\n+ acrLoaMap.put(\"copper\", 0);\n+ acrLoaMap.put(\"silver\", 1);\n+ acrLoaMap.put(\"gold\", 2);\n+ realmRep.getAttributes().put(Constants.ACR_LOA_MAP, JsonSerialization.writeValueAsString(acrLoaMap));\n+ adminClient.realm(\"test\").update(realmRep);\n+\n+ OIDCClientRepresentation clientRep = createRep();\n+ clientRep.setDefaultAcrValues(Arrays.asList(\"silver\", \"foo\"));\n+ try {\n+ OIDCClientRepresentation response = reg.oidc().create(clientRep);\n+ fail(\"Expected 400\");\n+ } catch (ClientRegistrationException e) {\n+ assertEquals(400, ((HttpErrorException) e.getCause()).getStatusLine().getStatusCode());\n+ }\n+\n+ clientRep.setDefaultAcrValues(Arrays.asList(\"silver\", \"gold\"));\n+ OIDCClientRepresentation response = reg.oidc().create(clientRep);\n+ Assert.assertNames(response.getDefaultAcrValues(), \"silver\", \"gold\");\n+\n+ // Test Keycloak representation\n+ ClientRepresentation kcClient = getClient(response.getClientId());\n+ OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient);\n+ Assert.assertNames(config.getAttributeMultivalued(Constants.DEFAULT_ACR_VALUES), \"silver\", \"gold\");\n+\n+ // Revert realm acr-to-loa mappings\n+ realmRep.getAttributes().remove(Constants.ACR_LOA_MAP);\n+ adminClient.realm(\"test\").update(realmRep);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java", "diff": "@@ -22,6 +22,8 @@ import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n+\n+import javax.ws.rs.BadRequestException;\nimport javax.ws.rs.core.UriBuilder;\nimport org.jboss.arquillian.graphene.page.Page;\nimport org.junit.After;\n@@ -37,6 +39,7 @@ import org.keycloak.authentication.authenticators.conditional.ConditionalLoaAuth\nimport org.keycloak.events.Details;\nimport org.keycloak.models.AuthenticationExecutionModel.Requirement;\nimport org.keycloak.models.Constants;\n+import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\nimport org.keycloak.representations.ClaimsRepresentation;\nimport org.keycloak.representations.IDToken;\nimport org.keycloak.representations.idm.ClientRepresentation;\n@@ -337,6 +340,79 @@ public class LevelOfAssuranceFlowTest extends AbstractTestRealmKeycloakTest {\ntestRealm().update(realmRep);\n}\n+ @Test\n+ public void testClientDefaultAcrValues() {\n+ ClientResource testClient = ApiUtil.findClientByClientId(testRealm(), \"test-app\");\n+ ClientRepresentation testClientRep = testClient.toRepresentation();\n+ OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, Arrays.asList(\"silver\", \"gold\"));\n+ testClient.update(testClientRep);\n+\n+ // Should request client to authenticate with silver\n+ oauth.openLoginForm();\n+ authenticateWithUsername();\n+ assertLoggedInWithAcr(\"silver\");\n+\n+ // Re-configure to level gold\n+ OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, Arrays.asList(\"gold\"));\n+ testClient.update(testClientRep);\n+ oauth.openLoginForm();\n+ authenticateWithPassword();\n+ assertLoggedInWithAcr(\"gold\");\n+\n+ // Value from essential ACR should have preference\n+ openLoginFormWithAcrClaim(true, \"silver\");\n+ assertLoggedInWithAcr(\"0\");\n+\n+ // Value from non-essential ACR should have preference\n+ openLoginFormWithAcrClaim(false, \"silver\");\n+ assertLoggedInWithAcr(\"0\");\n+\n+ // Revert\n+ testClientRep.getAttributes().put(Constants.DEFAULT_ACR_VALUES, null);\n+ testClient.update(testClientRep);\n+ }\n+\n+ @Test\n+ public void testClientDefaultAcrValuesValidation() throws IOException {\n+ // Setup realm acr-to-loa mapping\n+ RealmRepresentation realmRep = testRealm().toRepresentation();\n+ Map<String, Integer> acrLoaMap = new HashMap<>();\n+ acrLoaMap.put(\"realm:copper\", 0);\n+ acrLoaMap.put(\"realm:silver\", 1);\n+ realmRep.getAttributes().put(Constants.ACR_LOA_MAP, JsonSerialization.writeValueAsString(acrLoaMap));\n+ testRealm().update(realmRep);\n+\n+ // Value \"foo\" not used in any ACR-To-Loa mapping\n+ ClientResource testClient = ApiUtil.findClientByClientId(testRealm(), \"test-app\");\n+ ClientRepresentation testClientRep = testClient.toRepresentation();\n+ OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, Arrays.asList(\"silver\", \"2\", \"foo\"));\n+ try {\n+ testClient.update(testClientRep);\n+ Assert.fail(\"Should not successfully update client\");\n+ } catch (BadRequestException bre) {\n+ // Expected\n+ }\n+\n+ // Value \"5\" too big\n+ OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, Arrays.asList(\"silver\", \"2\", \"5\"));\n+ try {\n+ testClient.update(testClientRep);\n+ Assert.fail(\"Should not successfully update client\");\n+ } catch (BadRequestException bre) {\n+ // Expected\n+ }\n+\n+ // Should be fine\n+ OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, Arrays.asList(\"silver\", \"2\"));\n+ testClient.update(testClientRep);\n+\n+ // Revert\n+ testClientRep.getAttributes().put(Constants.DEFAULT_ACR_VALUES, null);\n+ testClient.update(testClientRep);\n+ realmRep.getAttributes().remove(Constants.ACR_LOA_MAP);\n+ testRealm().update(realmRep);\n+ }\n+\npublic void openLoginFormWithAcrClaim(boolean essential, String... acrValues) {\nopenLoginFormWithAcrClaim(oauth, essential, acrValues);\n}\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/messages/admin-messages_en.properties", "new_path": "themes/src/main/resources/theme/base/admin/messages/admin-messages_en.properties", "diff": "@@ -1943,6 +1943,8 @@ use-idtoken-as-detached-signature.tooltip=This makes ID token returned from Auth\nacr-loa-map=ACR to LoA Mapping\nacr-loa-map.tooltip=Define which ACR (Authentication Context Class Reference) value is mapped to which LoA (Level of Authentication). The ACR can be any value, whereas the LoA must be numeric. The LoA typically refers to the numbers configured as levels in the conditions in the authentication flow. The ACR refers to the value used in the OIDC/SAML authorization request and returned to client in the tokens.\nacr-loa-map-client.tooltip=Define which ACR (Authentication Context Class Reference) value is mapped to which LoA (Level of Authentication). The ACR can be any value, whereas the LoA must be numeric. This is recommended to be configured at the realm level where it is shared for all the clients. If you configure at the client level, the client mapping will take precedence over the mapping from the realm level.\n+default-acr-values=Default ACR Values\n+default-acr-values.tooltip=Default values to be used as voluntary ACR in case that there is no explicit ACR requested by 'claims' or 'acr_values' parameter in the OIDC request.\nkey-not-allowed-here=Key '{{character}}' is not allowed here.\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/js/controllers/clients.js", "new_path": "themes/src/main/resources/theme/base/admin/resources/js/controllers/clients.js", "diff": "@@ -1107,7 +1107,7 @@ module.controller('ClientDetailCtrl', function($scope, realm, client, flows, $ro\n}\n$scope.flows.push(emptyFlow)\n$scope.clientFlows.push(emptyFlow)\n-\n+ var deletedSomeDefaultAcrValue = false;\n$scope.accessTypes = [\n@@ -1477,6 +1477,13 @@ module.controller('ClientDetailCtrl', function($scope, realm, client, flows, $ro\n$scope.client.requestUris = [];\n}\n+ if ($scope.client.attributes[\"default.acr.values\"] && $scope.client.attributes[\"default.acr.values\"].length > 0) {\n+ $scope.defaultAcrValues = $scope.client.attributes[\"default.acr.values\"].split(\"##\");\n+ } else {\n+ $scope.defaultAcrValues = [];\n+ }\n+ deletedSomeDefaultAcrValue = false;\n+\ntry {\n$scope.acrLoaMap = JSON.parse($scope.client.attributes[\"acr.loa.map\"] || \"{}\");\n} catch (e) {\n@@ -1680,6 +1687,10 @@ module.controller('ClientDetailCtrl', function($scope, realm, client, flows, $ro\nif ($scope.newRequestUri && $scope.newRequestUri.length > 0) {\nreturn true;\n}\n+ if ($scope.newDefaultAcrValue && $scope.newDefaultAcrValue.length > 0) {\n+ return true;\n+ }\n+ if (deletedSomeDefaultAcrValue) return true;\nif ($scope.newAcr && $scope.newAcr.length > 0 && $scope.newLoa && $scope.newLoa.length > 0) {\nreturn true;\n}\n@@ -1795,6 +1806,10 @@ module.controller('ClientDetailCtrl', function($scope, realm, client, flows, $ro\n$scope.changed = isChanged();\n}, true);\n+ $scope.$watch('newDefaultAcrValue', function() {\n+ $scope.changed = isChanged();\n+ }, true);\n+\n$scope.deleteWebOrigin = function(index) {\n$scope.clientEdit.webOrigins.splice(index, 1);\n}\n@@ -1809,6 +1824,15 @@ module.controller('ClientDetailCtrl', function($scope, realm, client, flows, $ro\n$scope.clientEdit.requestUris.push($scope.newRequestUri);\n$scope.newRequestUri = \"\";\n}\n+ $scope.deleteDefaultAcrValue = function(index) {\n+ $scope.defaultAcrValues.splice(index, 1);\n+ deletedSomeDefaultAcrValue = true;\n+ $scope.changed = isChanged();\n+ }\n+ $scope.addDefaultAcrValue = function() {\n+ $scope.defaultAcrValues.push($scope.newDefaultAcrValue);\n+ $scope.newDefaultAcrValue = \"\";\n+ }\n$scope.deleteRedirectUri = function(index) {\n$scope.clientEdit.redirectUris.splice(index, 1);\n}\n@@ -1840,6 +1864,15 @@ module.controller('ClientDetailCtrl', function($scope, realm, client, flows, $ro\n}\ndelete $scope.clientEdit.requestUris;\n+ if ($scope.newDefaultAcrValue && $scope.newDefaultAcrValue.length > 0) {\n+ $scope.addDefaultAcrValue();\n+ }\n+ if ($scope.defaultAcrValues && $scope.defaultAcrValues.length > 0) {\n+ $scope.clientEdit.attributes[\"default.acr.values\"] = $scope.defaultAcrValues.join(\"##\");\n+ } else {\n+ $scope.clientEdit.attributes[\"default.acr.values\"] = null;\n+ }\n+\nif ($scope.samlArtifactBinding == true) {\n$scope.clientEdit.attributes[\"saml.artifact.binding\"] = \"true\";\n} else {\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/client-detail.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/client-detail.html", "diff": "<kc-tooltip>{{:: 'require-pushed-authorization-requests.tooltip' | translate}}</kc-tooltip>\n</div>\n- <div class=\"form-group clearfix block\" data-ng-show=\"(!clientEdit.bearerOnly && protocol == 'openid-connect') && (clientEdit.standardFlowEnabled || clientEdit.directAccessGrantsEnabled || clientEdit.implicitFlowEnabled)\">\n+ <div class=\"form-group clearfix block\" data-ng-show=\"!clientEdit.bearerOnly && protocol == 'openid-connect'\">\n<label class=\"col-md-2 control-label\" for=\"newAcr\">{{:: 'acr-loa-map' | translate}}</label>\n<div class=\"col-sm-6\">\n<div class=\"input-group input-map\" ng-repeat=\"(acr, loa) in acrLoaMap\">\n</div>\n<kc-tooltip>{{:: 'acr-loa-map-client.tooltip' | translate}}</kc-tooltip>\n</div>\n+\n+ <div class=\"form-group\" data-ng-show=\"!clientEdit.bearerOnly && protocol == 'openid-connect'\">\n+ <label class=\"col-md-2 control-label\" for=\"newDefaultAcrValue\">{{:: 'default-acr-values' | translate}}</label>\n+\n+ <div class=\"col-sm-6\">\n+ <div class=\"input-group\" ng-repeat=\"(i, defaultAcrValue) in defaultAcrValues track by $index\">\n+ <input class=\"form-control\" ng-model=\"defaultAcrValues[i]\">\n+ <div class=\"input-group-btn\">\n+ <button class=\"btn btn-default\" type=\"button\" data-ng-click=\"deleteDefaultAcrValue($index)\"><span class=\"fa fa-minus\"></span></button>\n+ </div>\n+ </div>\n+\n+ <div class=\"input-group\">\n+ <input class=\"form-control\" ng-model=\"newDefaultAcrValue\" id=\"newDefaultAcrValue\">\n+ <div class=\"input-group-btn\">\n+ <button class=\"btn btn-default\" type=\"button\" data-ng-click=\"newDefaultAcrValue.length > 0 && addDefaultAcrValue()\"><span class=\"fa fa-plus\"></span></button>\n+ </div>\n+ </div>\n+ </div>\n+\n+ <kc-tooltip>{{:: 'default-acr-values.tooltip' | translate}}</kc-tooltip>\n+ </div>\n+\n</fieldset>\n<fieldset>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Option for client to specify default acr level (#10364) Closes #10160
339,618
22.02.2022 08:19:45
-3,600
9358535161721fb14f6efdb8a68888945de0b6e6
Fix admin user creation message when calling quarkus welcomepage from remote For wildfly, everything is as before. For Quarkus, we check if http is enabled and provide the right port and scheme if so, and also we are relative-path aware. Closes
[ { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/services/resources/QuarkusWelcomeResource.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/services/resources/QuarkusWelcomeResource.java", "diff": "@@ -24,10 +24,10 @@ import org.keycloak.common.util.Base64Url;\nimport org.keycloak.common.util.MimeTypeUtil;\nimport org.keycloak.common.util.SecretGenerator;\nimport org.keycloak.models.KeycloakSession;\n+import org.keycloak.quarkus.runtime.configuration.Configuration;\nimport org.keycloak.services.ForbiddenException;\nimport org.keycloak.services.ServicesLogger;\nimport org.keycloak.services.managers.ApplianceBootstrap;\n-import org.keycloak.services.resources.WelcomeResource;\nimport org.keycloak.services.util.CacheControlUtil;\nimport org.keycloak.services.util.CookieHelper;\nimport org.keycloak.theme.FreeMarkerUtil;\n@@ -188,6 +188,11 @@ public class QuarkusWelcomeResource {\nboolean isLocal = isLocal();\nmap.put(\"localUser\", isLocal);\n+ String localAdminUrl = getLocalAdminUrl();\n+\n+ map.put(\"localAdminUrl\", localAdminUrl);\n+ map.put(\"adminUserCreationMessage\", \"or set the environment variables KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD before starting the server\");\n+\nif (isLocal) {\nString stateChecker = setCsrfCookie();\nmap.put(\"stateChecker\", stateChecker);\n@@ -211,6 +216,21 @@ public class QuarkusWelcomeResource {\n}\n}\n+ private String getLocalAdminUrl() {\n+ boolean isHttpEnabled = Boolean.parseBoolean(Configuration.getConfigValue(\"kc.http-enabled\").getValue());\n+ String configPath = Configuration.getConfigValue(\"kc.http-relative-path\").getValue();\n+\n+ if (!configPath.startsWith(\"/\")) {\n+ configPath = \"/\" + configPath;\n+ }\n+\n+ String configPort = isHttpEnabled ? Configuration.getConfigValue(\"kc.http-port\").getValue() : Configuration.getConfigValue(\"kc.https-port\").getValue() ;\n+\n+ String scheme = isHttpEnabled ? \"http://\" : \"https://\";\n+\n+ return scheme + \"localhost:\" + configPort + configPath;\n+ }\n+\nprivate Theme getTheme() {\ntry {\nreturn session.theme().getTheme(Theme.Type.WELCOME);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/WelcomeResource.java", "new_path": "services/src/main/java/org/keycloak/services/resources/WelcomeResource.java", "diff": "@@ -181,7 +181,6 @@ public class WelcomeResource {\nmap.put(\"properties\", theme.getProperties());\nmap.put(\"adminUrl\", session.getContext().getUri(UrlType.ADMIN).getBaseUriBuilder().path(\"/admin/\").build());\n-\nmap.put(\"resourcesPath\", \"resources/\" + Version.RESOURCES_VERSION + \"/\" + theme.getType().toString().toLowerCase() +\"/\" + theme.getName());\nmap.put(\"resourcesCommonPath\", \"resources/\" + Version.RESOURCES_VERSION + \"/common/keycloak\");\n@@ -190,6 +189,8 @@ public class WelcomeResource {\nif (bootstrap) {\nboolean isLocal = isLocal();\nmap.put(\"localUser\", isLocal);\n+ map.put(\"localAdminUrl\", \"http://localhost:8080/auth\");\n+ map.put(\"adminUserCreationMessage\",\"or use the add-user-keycloak script\");\nif (isLocal) {\nString stateChecker = setCsrfCookie();\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak/welcome/index.ftl", "new_path": "themes/src/main/resources/theme/keycloak/welcome/index.ftl", "diff": "<p>Please create an initial admin user to get started.</p>\n<#else>\n<p class=\"welcome-message\">\n- <img src=\"welcome-content/alert.png\">You need local access to create the initial admin user. <br><br>Open <a href=\"http://localhost:8080/auth\">http://localhost:8080/auth</a>\n- <br>or use the add-user-keycloak script.\n+ <img src=\"welcome-content/alert.png\">You need local access to create the initial admin user. <br><br>Open <a href=\"${localAdminUrl}\">${localAdminUrl}</a>\n+ <br>${adminUserCreationMessage}.\n</p>\n</#if>\n</#if>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Fix admin user creation message when calling quarkus welcomepage from remote (#10362) For wildfly, everything is as before. For Quarkus, we check if http is enabled and provide the right port and scheme if so, and also we are relative-path aware. Closes #10335
339,217
22.02.2022 19:10:12
-39,600
7fdd18ac866f054a1d383cf4cfba3ed4acbc2b32
Update enabletls.adoc Correction to command line
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/enabletls.adoc", "new_path": "docs/guides/src/main/server/enabletls.adoc", "diff": "@@ -57,7 +57,7 @@ You can configure the location of this truststore by running the following comma\n=== Setting the truststore password\nYou can set a secure password for your truststore using the `https.trust-store.password` option:\n-<@kc.start parameters=\"--https.trust-store.password=<value>\"/>\n+<@kc.start parameters=\"--https-trust-store-password=<value>\"/>\nIf no password is set, the default password `password` is used.\n== Securing credentials\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Update enabletls.adoc (#10369) Correction to command line
339,682
22.02.2022 20:40:05
-3,600
9fd86ac27f50708b8a1327f87fd84d21b46315e7
Changes Doctype in base theme to <!DOCTYPE HTML> Closes:
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/login/template.ftl", "new_path": "themes/src/main/resources/theme/base/login/template.ftl", "diff": "<#macro registrationLayout bodyClass=\"\" displayInfo=false displayMessage=true displayRequiredFields=false showAnotherWayIfPresent=true>\n-<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n-<html xmlns=\"http://www.w3.org/1999/xhtml\" class=\"${properties.kcHtmlClass!}\">\n+<!DOCTYPE html>\n+<html class=\"${properties.kcHtmlClass!}\">\n<head>\n<meta charset=\"utf-8\">\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Changes Doctype in base theme to <!DOCTYPE HTML> (#10271) Closes: #10157 Co-authored-by: Michael Rosenberger <[email protected]>
339,618
17.02.2022 12:52:20
-3,600
19a17e79bad03c7d46c28fbcade7863a35713a0e
Change tx driver handling. Introduce a non-tx driver for the vendors and map based on new build option transaction-tx-enabled Closes and others.
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/db.adoc", "new_path": "docs/guides/src/main/server/db.adoc", "diff": "<@tmpl.guide\ntitle=\"Configuring the database\"\nsummary=\"An overview about how to configure relational databases\"\n- includedOptions=\"db db-*\">\n+ includedOptions=\"db db-* transaction-xa-enabled\">\nIn this guide, you are going to understand how to configure the server to store data using different relational databases. You should also learn\nYou will also learn what databases are supported by the server.\n@@ -119,4 +119,11 @@ By default, the maximum timeout for this lock is 900 seconds. If a node is waiti\n<@kc.start parameters=\"--spi-dblock-jpa-lock-wait-timeout 900\"/>\n+== Using Database Vendors without XA transaction support\n+Keycloak uses XA transactions and the appropriate database drivers by default. There are vendors like Azure SQL and MariaDB Galera, that do not support or rely on the XA transaction mechanism. To use Keycloak without XA transaction support using the appropriate jdbc driver, invoke the following command:\n+\n+<@kc.build parameters=\"--db=<vendor> --transaction-xa-enabled=false\"/>\n+\n+Keycloak will automatically choose the appropriate jdbc driver for your vendor.\n+\n</@tmpl.guide>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ConfigCategory.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ConfigCategory.java", "diff": "@@ -4,13 +4,14 @@ public enum ConfigCategory {\n// ordered by name asc\nCLUSTERING(\"Cluster\", 10),\nDATABASE(\"Database\", 20),\n- FEATURE(\"Feature\", 30),\n- HOSTNAME(\"Hostname\", 40),\n- HTTP(\"HTTP/TLS\", 50),\n- METRICS(\"Metrics\", 60),\n- PROXY(\"Proxy\", 70),\n- VAULT(\"Vault\", 80),\n- LOGGING(\"Logging\", 90),\n+ TRANSACTION(\"Transaction\",30),\n+ FEATURE(\"Feature\", 40),\n+ HOSTNAME(\"Hostname\", 50),\n+ HTTP(\"HTTP/TLS\", 60),\n+ METRICS(\"Metrics\", 70),\n+ PROXY(\"Proxy\", 80),\n+ VAULT(\"Vault\", 90),\n+ LOGGING(\"Logging\", 100),\nGENERAL(\"General\", 999);\nprivate final String heading;\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/DatabasePropertyMappers.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/DatabasePropertyMappers.java", "diff": "@@ -2,8 +2,10 @@ package org.keycloak.quarkus.runtime.configuration.mappers;\nimport io.quarkus.datasource.common.runtime.DatabaseKind;\nimport io.smallrye.config.ConfigSourceInterceptorContext;\n+import io.smallrye.config.ConfigValue;\nimport org.keycloak.quarkus.runtime.storage.database.Database;\n+import java.util.List;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\n@@ -26,9 +28,9 @@ final class DatabasePropertyMappers {\n.build(),\nbuilder().from(\"db-driver\")\n.mapFrom(\"db\")\n- .defaultValue(Database.getDriver(\"dev-file\").get())\n+ .defaultValue(Database.getDriver(\"dev-file\", true).get())\n.to(\"quarkus.datasource.jdbc.driver\")\n- .transformer((db, context) -> Database.getDriver(db).orElse(db))\n+ .transformer(DatabasePropertyMappers::getXaOrNonXaDriver)\n.hidden(true)\n.build(),\nbuilder().from(\"db\").\n@@ -39,11 +41,6 @@ final class DatabasePropertyMappers {\n.paramLabel(\"vendor\")\n.expectedValues(asList(Database.getAliases()))\n.build(),\n- builder().from(\"db-tx-type\")\n- .defaultValue(\"xa\")\n- .to(\"quarkus.datasource.jdbc.transactions\")\n- .hidden(true)\n- .build(),\nbuilder().from(\"db-url\")\n.to(\"quarkus.datasource.jdbc.url\")\n.mapFrom(\"db\")\n@@ -106,6 +103,14 @@ final class DatabasePropertyMappers {\n};\n}\n+ private static String getXaOrNonXaDriver(String db, ConfigSourceInterceptorContext context) {\n+ ConfigValue xaEnabledConfigValue = context.proceed(\"kc.transaction-xa-enabled\");\n+\n+ boolean isXaEnabled = xaEnabledConfigValue == null || Boolean.parseBoolean(xaEnabledConfigValue.getValue());\n+\n+ return Database.getDriver(db, isXaEnabled).orElse(db);\n+ }\n+\nprivate static BiFunction<String, ConfigSourceInterceptorContext, String> toDatabaseKind() {\nreturn (db, context) -> {\nOptional<String> databaseKind = Database.getDatabaseKind(db);\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java", "diff": "@@ -31,6 +31,7 @@ public final class PropertyMappers {\nMAPPERS.addAll(VaultPropertyMappers.getVaultPropertyMappers());\nMAPPERS.addAll(FeaturePropertyMappers.getMappers());\nMAPPERS.addAll(LoggingPropertyMappers.getMappers());\n+ MAPPERS.addAll(TransactionPropertyMappers.getTransactionPropertyMappers());\n}\npublic static ConfigValue getValue(ConfigSourceInterceptorContext context, String name) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/TransactionPropertyMappers.java", "diff": "+package org.keycloak.quarkus.runtime.configuration.mappers;\n+\n+import io.smallrye.config.ConfigSourceInterceptorContext;\n+\n+import java.util.Arrays;\n+\n+public class TransactionPropertyMappers {\n+\n+ private TransactionPropertyMappers(){}\n+\n+ public static PropertyMapper[] getTransactionPropertyMappers() {\n+ return new PropertyMapper[] {\n+ builder().from(\"transaction-xa-enabled\")\n+ .to(\"quarkus.datasource.jdbc.transactions\")\n+ .defaultValue(Boolean.TRUE.toString())\n+ .description(\"Manually override the transaction type. Transaction type XA and the appropriate driver is used by default.\")\n+ .paramLabel(Boolean.TRUE + \"|\" + Boolean.FALSE)\n+ .expectedValues(Arrays.asList(Boolean.TRUE.toString(), Boolean.FALSE.toString()))\n+ .isBuildTimeProperty(true)\n+ .transformer(TransactionPropertyMappers::getQuarkusTransactionsValue)\n+ .build(),\n+ };\n+ }\n+\n+ private static String getQuarkusTransactionsValue(String txValue, ConfigSourceInterceptorContext context) {\n+ boolean isXaEnabled = Boolean.parseBoolean(txValue);\n+\n+ if (isXaEnabled) {\n+ return \"xa\";\n+ }\n+\n+ return \"enabled\";\n+ }\n+\n+ private static PropertyMapper.Builder builder() {\n+ return PropertyMapper.builder(ConfigCategory.TRANSACTION);\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/Database.java", "new_path": "quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/Database.java", "diff": "@@ -68,14 +68,18 @@ public final class Database {\nreturn Optional.of(vendor.defaultUrl.apply(alias));\n}\n- public static Optional<String> getDriver(String alias) {\n+ public static Optional<String> getDriver(String alias, boolean isXaEnabled) {\nVendor vendor = DATABASES.get(alias);\nif (vendor == null) {\nreturn Optional.empty();\n}\n- return Optional.of(vendor.driver);\n+ if (isXaEnabled) {\n+ return Optional.of(vendor.xaDriver);\n+ }\n+\n+ return Optional.of(vendor.nonXaDriver);\n}\npublic static Optional<String> getDialect(String alias) {\n@@ -95,6 +99,7 @@ public final class Database {\nprivate enum Vendor {\nH2(\"h2\",\n\"org.h2.jdbcx.JdbcDataSource\",\n+ \"org.h2.Driver\",\n\"io.quarkus.hibernate.orm.runtime.dialect.QuarkusH2Dialect\",\nnew Function<String, String>() {\n@Override\n@@ -112,19 +117,21 @@ public final class Database {\n),\nMYSQL(\"mysql\",\n\"com.mysql.cj.jdbc.MysqlXADataSource\",\n+ \"com.mysql.cj.jdbc.Driver\",\n\"org.hibernate.dialect.MySQL8Dialect\",\n-\n\"jdbc:mysql://${kc.db-url-host:localhost}/${kc.db-url-database:keycloak}${kc.db-url-properties:}\",\nasList(\"org.keycloak.connections.jpa.updater.liquibase.UpdatedMySqlDatabase\")\n),\nMARIADB(\"mariadb\",\n\"org.mariadb.jdbc.MySQLDataSource\",\n+ \"org.mariadb.jdbc.Driver\",\n\"org.hibernate.dialect.MariaDBDialect\",\n\"jdbc:mariadb://${kc.db-url-host:localhost}/${kc.db-url-database:keycloak}${kc.db-url-properties:}\",\nasList(\"org.keycloak.connections.jpa.updater.liquibase.UpdatedMariaDBDatabase\")\n),\nPOSTGRES(\"postgresql\",\n\"org.postgresql.xa.PGXADataSource\",\n+ \"org.postgresql.Driver\",\n\"io.quarkus.hibernate.orm.runtime.dialect.QuarkusPostgreSQL10Dialect\",\n\"jdbc:postgresql://${kc.db-url-host:localhost}/${kc.db-url-database:keycloak}${kc.db-url-properties:}\",\nasList(\"liquibase.database.core.PostgresDatabase\",\n@@ -133,6 +140,7 @@ public final class Database {\n),\nMSSQL(\"mssql\",\n\"com.microsoft.sqlserver.jdbc.SQLServerXADataSource\",\n+ \"com.microsoft.sqlserver.jdbc.SQLServerDriver\",\n\"org.hibernate.dialect.SQLServer2016Dialect\",\n\"jdbc:sqlserver://${kc.db-url-host:localhost}:1433;databaseName=${kc.db-url-database:keycloak}${kc.db-url-properties:}\",\nasList(\"org.keycloak.quarkus.runtime.storage.database.liquibase.database.CustomMSSQLDatabase\"),\n@@ -140,38 +148,36 @@ public final class Database {\n),\nORACLE(\"oracle\",\n\"oracle.jdbc.xa.client.OracleXADataSource\",\n+ \"oracle.jdbc.driver.OracleDriver\",\n\"org.hibernate.dialect.Oracle12cDialect\",\n\"jdbc:oracle:thin:@//${kc.db-url-host:localhost}:1521/${kc.db-url-database:keycloak}\",\nasList(\"liquibase.database.core.OracleDatabase\")\n);\nfinal String databaseKind;\n- final String driver;\n+ final String xaDriver;\n+ final String nonXaDriver;\nfinal Function<String, String> dialect;\nfinal Function<String, String> defaultUrl;\nfinal List<String> liquibaseTypes;\nfinal String[] aliases;\n- Vendor(String databaseKind, String driver, String dialect, String defaultUrl, List<String> liquibaseTypes,\n+ Vendor(String databaseKind, String xaDriver, String nonXaDriver, String dialect, String defaultUrl, List<String> liquibaseTypes,\nString... aliases) {\n- this(databaseKind, driver, alias -> dialect, alias -> defaultUrl, liquibaseTypes, aliases);\n- }\n-\n- Vendor(String databaseKind, String driver, String dialect, Function<String, String> defaultUrl,\n- List<String> liquibaseTypes, String... aliases) {\n- this(databaseKind, driver, alias -> dialect, defaultUrl, liquibaseTypes, aliases);\n+ this(databaseKind, xaDriver, nonXaDriver, alias -> dialect, alias -> defaultUrl, liquibaseTypes, aliases);\n}\n- Vendor(String databaseKind, String driver, Function<String, String> dialect, String defaultUrl,\n+ Vendor(String databaseKind, String xaDriver, String nonXaDriver, String dialect, Function<String, String> defaultUrl,\nList<String> liquibaseTypes, String... aliases) {\n- this(databaseKind, driver, dialect, alias -> defaultUrl, liquibaseTypes, aliases);\n+ this(databaseKind, xaDriver, nonXaDriver, alias -> dialect, defaultUrl, liquibaseTypes, aliases);\n}\n- Vendor(String databaseKind, String driver, Function<String, String> dialect, Function<String, String> defaultUrl,\n+ Vendor(String databaseKind, String xaDriver, String nonXaDriver, Function<String, String> dialect, Function<String, String> defaultUrl,\nList<String> liquibaseTypes,\nString... aliases) {\nthis.databaseKind = databaseKind;\n- this.driver = driver;\n+ this.xaDriver = xaDriver;\n+ this.nonXaDriver = nonXaDriver;\nthis.dialect = dialect;\nthis.defaultUrl = defaultUrl;\nthis.liquibaseTypes = liquibaseTypes;\n" }, { "change_type": "MODIFY", "old_path": "quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java", "new_path": "quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java", "diff": "@@ -380,7 +380,7 @@ public class ConfigurationTest {\npublic void testDatabaseDriverSetExplicitly() {\nSystem.setProperty(CLI_ARGS, \"--db=mssql\" + ARG_SEPARATOR + \"--db-url=jdbc:sqlserver://localhost/keycloak\");\nSystem.setProperty(\"kc.db-driver\", \"com.microsoft.sqlserver.jdbc.SQLServerDriver\");\n- System.setProperty(\"kc.db-tx-type\", \"enabled\");\n+ System.setProperty(\"kc.transaction-xa-enabled\", \"false\");\nassertTrue(System.getProperty(CLI_ARGS, \"\").contains(\"mssql\"));\nSmallRyeConfig config = createConfig();\nassertEquals(\"jdbc:sqlserver://localhost/keycloak\", config.getConfigValue(\"quarkus.datasource.jdbc.url\").getValue());\n@@ -389,6 +389,23 @@ public class ConfigurationTest {\nassertEquals(\"enabled\", config.getConfigValue(\"quarkus.datasource.jdbc.transactions\").getValue());\n}\n+ @Test\n+ public void testTransactionTypeChangesDriver() {\n+ System.setProperty(CLI_ARGS, \"--db=mssql\" + ARG_SEPARATOR + \"--transaction-xa-enabled=false\");\n+ assertTrue(System.getProperty(CLI_ARGS, \"\").contains(\"mssql\"));\n+\n+ SmallRyeConfig config = createConfig();\n+ assertEquals(\"com.microsoft.sqlserver.jdbc.SQLServerDriver\", config.getConfigValue(\"quarkus.datasource.jdbc.driver\").getValue());\n+ assertEquals(\"enabled\", config.getConfigValue(\"quarkus.datasource.jdbc.transactions\").getValue());\n+\n+ System.setProperty(CLI_ARGS, \"--db=mssql\" + ARG_SEPARATOR + \"--transaction-xa-enabled=true\");\n+ assertTrue(System.getProperty(CLI_ARGS, \"\").contains(\"mssql\"));\n+ SmallRyeConfig config2 = createConfig();\n+\n+ assertEquals(\"com.microsoft.sqlserver.jdbc.SQLServerXADataSource\", config2.getConfigValue(\"quarkus.datasource.jdbc.driver\").getValue());\n+ assertEquals(\"xa\", config2.getConfigValue(\"quarkus.datasource.jdbc.transactions\").getValue());\n+ }\n+\n@Test\npublic void testResolveMetricsOption() {\nSystem.setProperty(CLI_ARGS, \"--metrics-enabled=true\");\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/MSSQLStartDatabaseTest.java", "new_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/MSSQLStartDatabaseTest.java", "diff": "@@ -36,7 +36,7 @@ public class MSSQLStartDatabaseTest extends AbstractStartDabataseTest {\n*/\n@Override\n@Test\n- @Launch({ \"-Dkc.db-tx-type=enabled\", \"-Dkc.db-driver=com.microsoft.sqlserver.jdbc.SQLServerDriver\", \"start-dev\" })\n+ @Launch({ \"--transaction-xa-enabled=false\", \"start-dev\" })\nvoid testSuccessful(LaunchResult result) {\nCLIResult cliResult = (CLIResult) result;\ncliResult.assertStartedDevMode();\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/dist/CustomTransactionDistTest.java", "new_path": "quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/dist/CustomTransactionDistTest.java", "diff": "@@ -28,21 +28,7 @@ import io.quarkus.test.junit.main.LaunchResult;\npublic class CustomTransactionDistTest {\n@Test\n- @Launch({ \"-Dkc.db-tx-type=enabled\", \"-Dkc.db-driver=org.postgresql.xa.PGXADataSource\", \"build\", \"--db=postgres\" })\n- void failNoXAUsingXADriver(LaunchResult result) {\n- CLIResult cliResult = (CLIResult) result;\n- cliResult.assertError(\"Driver org.postgresql.xa.PGXADataSource is an XA datasource, but XA transactions have not been enabled on the default datasource\");\n- }\n-\n- @Test\n- @Launch({ \"-Dkc.db-driver=com.microsoft.sqlserver.jdbc.SQLServerDriver\", \"build\", \"--db=mssql\" })\n- void failXAUsingNonXADriver(LaunchResult result) {\n- CLIResult cliResult = (CLIResult) result;\n- cliResult.assertError(\"Driver is not an XA dataSource, while XA has been enabled in the configuration of the default datasource\");\n- }\n-\n- @Test\n- @Launch({ \"-Dkc.db-tx-type=enabled\", \"-Dkc.db-driver=com.microsoft.sqlserver.jdbc.SQLServerDriver\", \"build\", \"--db=mssql\" })\n+ @Launch({ \"build\", \"--db=mssql\", \"--transaction-xa-enabled=false\" })\nvoid testNoXa(LaunchResult result) {\nCLIResult cliResult = (CLIResult) result;\ncliResult.assertBuild();\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt", "new_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt", "diff": "Binary files a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt and b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testBuildHelp.approved.txt differ\n" }, { "change_type": "MODIFY", "old_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testStartDevHelpAll.approved.txt", "new_path": "quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testStartDevHelpAll.approved.txt", "diff": "Binary files a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testStartDevHelpAll.approved.txt and b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/approvals/cli/help/HelpCommandTest.testStartDevHelpAll.approved.txt differ\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Change tx driver handling. Introduce a non-tx driver for the vendors and map based on new build option transaction-tx-enabled Closes #10191 and others. Co-authored-by: Pedro Igor <[email protected]>
339,240
23.02.2022 14:35:10
-3,600
91a51d276f3885cd90b205784dd07dcd69601f41
Realm translations are being added to the account console. For the account console translations are being fetched from the realm translations as well as from the theme properties. Closes
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java", "new_path": "services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java", "diff": "@@ -115,6 +115,7 @@ public class AccountConsole {\nLocale locale = session.getContext().resolveLocale(user);\nmap.put(\"locale\", locale.toLanguageTag());\nProperties messages = theme.getMessages(locale);\n+ messages.putAll(realm.getRealmLocalizationTextsByLocale(locale.toLanguageTag()));\nmap.put(\"msg\", new MessageFormatterMethod(locale, messages));\nmap.put(\"msgJSON\", messagesToJsonString(messages));\nmap.put(\"supportedLocales\", supportedLocales(messages));\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Realm translations are being added to the account console. (#10329) For the account console translations are being fetched from the realm translations as well as from the theme properties. Closes #10328
339,618
11.02.2022 10:27:08
-3,600
86dcec8e3ab00de25e6d872d473c504ca5a5bb2c
Update to Quarkus 2.7.1 Postgresql driver patch to 42.3.2 Closes
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<packaging>pom</packaging>\n<properties>\n- <quarkus.version>2.7.0.Final</quarkus.version>\n+ <quarkus.version>2.7.1.Final</quarkus.version>\n<!--\nPerforming a Wildfly upgrade? Run the:\n" }, { "change_type": "MODIFY", "old_path": "quarkus/pom.xml", "new_path": "quarkus/pom.xml", "diff": "<jackson.databind.version>${jackson.version}</jackson.databind.version>\n<hibernate.core.version>5.6.5.Final</hibernate.core.version>\n<mysql.driver.version>8.0.28</mysql.driver.version>\n- <postgresql.version>42.3.1</postgresql.version>\n+ <postgresql.version>42.3.2</postgresql.version>\n<microprofile-metrics-api.version>3.0</microprofile-metrics-api.version>\n<wildfly.common.version>1.5.4.Final-format-001</wildfly.common.version>\n<infinispan.version>13.0.5.Final</infinispan.version>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Update to Quarkus 2.7.1 Postgresql driver patch to 42.3.2 Closes #10111
339,433
07.10.2021 07:01:46
25,200
07d47cf6c2b5ef4f954bc941c4eebe0d2fc3a577
Removed exception handling on failed event persistence in the EventBuilder class.
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/events/EventBuilder.java", "new_path": "server-spi-private/src/main/java/org/keycloak/events/EventBuilder.java", "diff": "@@ -215,11 +215,7 @@ public class EventBuilder {\nif (store != null) {\nSet<String> eventTypes = realm.getEnabledEventTypesStream().collect(Collectors.toSet());\nif (!eventTypes.isEmpty() ? eventTypes.contains(event.getType().name()) : event.getType().isSaveByDefault()) {\n- try {\nstore.onEvent(event);\n- } catch (Throwable t) {\n- log.error(\"Failed to save event\", t);\n- }\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-19501 Removed exception handling on failed event persistence in the EventBuilder class.
339,500
11.02.2022 13:45:08
-3,600
6249e341777c1a733f0cc1e8b0511b76a373514b
Hot Rod map storage: Client scope no-downtime store
[ { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java", "new_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java", "diff": "@@ -1312,7 +1312,7 @@ public class RealmCacheSession implements CacheRealmProvider {\n@Override\npublic void removeClientScopes(RealmModel realm) {\n- realm.getClientScopesStream().map(ClientScopeModel::getId).forEach(id -> removeClientScope(realm, id));\n+ getClientScopesStream(realm).map(ClientScopeModel::getId).forEach(id -> removeClientScope(realm, id));\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/HotRodMapStorageProviderFactory.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/HotRodMapStorageProviderFactory.java", "diff": "@@ -22,11 +22,13 @@ import org.keycloak.Config;\nimport org.keycloak.common.Profile;\nimport org.keycloak.component.AmphibianProviderFactory;\nimport org.keycloak.models.ClientModel;\n+import org.keycloak.models.ClientScopeModel;\nimport org.keycloak.models.GroupModel;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.KeycloakSessionFactory;\nimport org.keycloak.models.RoleModel;\nimport org.keycloak.models.UserModel;\n+import org.keycloak.models.map.clientscope.MapClientScopeEntity;\nimport org.keycloak.models.map.group.MapGroupEntity;\nimport org.keycloak.models.map.role.MapRoleEntity;\nimport org.keycloak.models.map.storage.hotRod.role.HotRodRoleEntity;\n@@ -37,6 +39,8 @@ import org.keycloak.models.map.storage.hotRod.client.HotRodProtocolMapperEntityD\nimport org.keycloak.models.map.client.MapClientEntity;\nimport org.keycloak.models.map.client.MapProtocolMapperEntity;\nimport org.keycloak.models.map.common.DeepCloner;\n+import org.keycloak.models.map.storage.hotRod.clientscope.HotRodClientScopeEntity;\n+import org.keycloak.models.map.storage.hotRod.clientscope.HotRodClientScopeEntityDelegate;\nimport org.keycloak.models.map.storage.hotRod.common.HotRodEntityDescriptor;\nimport org.keycloak.models.map.storage.hotRod.connections.HotRodConnectionProvider;\nimport org.keycloak.models.map.storage.MapStorageProvider;\n@@ -65,6 +69,7 @@ public class HotRodMapStorageProviderFactory implements AmphibianProviderFactory\nprivate final static DeepCloner CLONER = new DeepCloner.Builder()\n.constructor(MapClientEntity.class, HotRodClientEntityDelegate::new)\n.constructor(MapProtocolMapperEntity.class, HotRodProtocolMapperEntityDelegate::new)\n+ .constructor(MapClientScopeEntity.class, HotRodClientScopeEntityDelegate::new)\n.constructor(MapGroupEntity.class, HotRodGroupEntityDelegate::new)\n.constructor(MapRoleEntity.class, HotRodRoleEntityDelegate::new)\n.constructor(MapUserEntity.class, HotRodUserEntityDelegate::new)\n@@ -81,6 +86,11 @@ public class HotRodMapStorageProviderFactory implements AmphibianProviderFactory\nHotRodClientEntity.class,\nHotRodClientEntityDelegate::new));\n+ ENTITY_DESCRIPTOR_MAP.put(ClientScopeModel.class,\n+ new HotRodEntityDescriptor<>(ClientScopeModel.class,\n+ HotRodClientScopeEntity.class,\n+ HotRodClientScopeEntityDelegate::new));\n+\n// Groups descriptor\nENTITY_DESCRIPTOR_MAP.put(GroupModel.class,\nnew HotRodEntityDescriptor<>(GroupModel.class,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/clientscope/HotRodClientScopeEntity.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.keycloak.models.map.storage.hotRod.clientscope;\n+\n+import org.infinispan.protostream.annotations.ProtoDoc;\n+import org.infinispan.protostream.annotations.ProtoField;\n+import org.keycloak.models.map.annotations.GenerateHotRodEntityImplementation;\n+import org.keycloak.models.map.client.MapProtocolMapperEntity;\n+import org.keycloak.models.map.clientscope.MapClientScopeEntity;\n+import org.keycloak.models.map.storage.hotRod.client.HotRodProtocolMapperEntity;\n+import org.keycloak.models.map.storage.hotRod.common.AbstractHotRodEntity;\n+import org.keycloak.models.map.storage.hotRod.common.HotRodAttributeEntityNonIndexed;\n+import org.keycloak.models.map.storage.hotRod.common.UpdatableHotRodEntityDelegateImpl;\n+\n+import java.util.Collection;\n+import java.util.LinkedHashSet;\n+import java.util.Objects;\n+import java.util.Optional;\n+import java.util.Set;\n+\n+@GenerateHotRodEntityImplementation(\n+ implementInterface = \"org.keycloak.models.map.clientscope.MapClientScopeEntity\",\n+ inherits = \"org.keycloak.models.map.storage.hotRod.clientscope.HotRodClientScopeEntity.AbstractHotRodClientScopeEntityDelegate\"\n+)\n+@ProtoDoc(\"@Indexed\")\n+public class HotRodClientScopeEntity extends AbstractHotRodEntity {\n+\n+ @ProtoField(number = 1, required = true)\n+ public int entityVersion = 1;\n+\n+ @ProtoField(number = 2, required = true)\n+ public String id;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 3)\n+ public String realmId;\n+\n+ @ProtoDoc(\"@Field(index = Index.YES, store = Store.YES)\")\n+ @ProtoField(number = 4)\n+ public String name;\n+\n+ @ProtoField(number = 5)\n+ public String protocol;\n+\n+ @ProtoField(number = 6)\n+ public String description;\n+\n+ @ProtoField(number = 7)\n+ public Collection<String> scopeMappings;\n+\n+ @ProtoField(number = 8)\n+ public Set<HotRodProtocolMapperEntity> protocolMappers;\n+\n+ @ProtoField(number = 9)\n+ public Set<HotRodAttributeEntityNonIndexed> attributes;\n+\n+ public static abstract class AbstractHotRodClientScopeEntityDelegate extends UpdatableHotRodEntityDelegateImpl<HotRodClientScopeEntity> implements MapClientScopeEntity {\n+\n+ @Override\n+ public String getId() {\n+ return getHotRodEntity().id;\n+ }\n+\n+ @Override\n+ public void setId(String id) {\n+ HotRodClientScopeEntity entity = getHotRodEntity();\n+ if (entity.id != null) throw new IllegalStateException(\"Id cannot be changed\");\n+ entity.id = id;\n+ entity.updated |= id != null;\n+ }\n+\n+ @Override\n+ public Optional<MapProtocolMapperEntity> getProtocolMapper(String id) {\n+ Set<MapProtocolMapperEntity> mappers = getProtocolMappers();\n+ if (mappers == null || mappers.isEmpty()) return Optional.empty();\n+\n+ return mappers.stream().filter(m -> Objects.equals(m.getId(), id)).findFirst();\n+ }\n+\n+ @Override\n+ public void removeProtocolMapper(String id) {\n+ HotRodClientScopeEntity entity = getHotRodEntity();\n+ entity.updated |= entity.protocolMappers != null && entity.protocolMappers.removeIf(m -> Objects.equals(m.id, id));\n+ }\n+ }\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ return HotRodClientScopeEntityDelegate.entityEquals(this, o);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return HotRodClientScopeEntityDelegate.entityHashCode(this);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/HotRodTypesUtils.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/HotRodTypesUtils.java", "diff": "@@ -21,6 +21,7 @@ import org.keycloak.models.map.common.AbstractEntity;\nimport org.keycloak.models.map.storage.hotRod.user.HotRodUserConsentEntity;\nimport org.keycloak.models.map.storage.hotRod.user.HotRodUserFederatedIdentityEntity;\n+import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\n@@ -38,7 +39,7 @@ public class HotRodTypesUtils {\n}\npublic static <MapKey, MapValue, SetValue> Map<MapKey, MapValue> migrateSetToMap(Set<SetValue> set, Function<SetValue, MapKey> keyProducer, Function<SetValue, MapValue> valueProducer) {\n- return set == null ? null : set.stream().collect(Collectors.toMap(keyProducer, valueProducer));\n+ return set == null ? null : set.stream().collect(HashMap::new, (m, v) -> m.put(keyProducer.apply(v), valueProducer.apply(v)), HashMap::putAll);\n}\npublic static <T, V> HotRodPair<T, V> createHotRodPairFromMapEntry(Map.Entry<T, V> entry) {\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/ProtoSchemaInitializer.java", "new_path": "model/map-hot-rod/src/main/java/org/keycloak/models/map/storage/hotRod/common/ProtoSchemaInitializer.java", "diff": "@@ -21,6 +21,7 @@ import org.infinispan.protostream.GeneratedSchema;\nimport org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;\nimport org.keycloak.models.map.storage.hotRod.client.HotRodClientEntity;\nimport org.keycloak.models.map.storage.hotRod.client.HotRodProtocolMapperEntity;\n+import org.keycloak.models.map.storage.hotRod.clientscope.HotRodClientScopeEntity;\nimport org.keycloak.models.map.storage.hotRod.group.HotRodGroupEntity;\nimport org.keycloak.models.map.storage.hotRod.role.HotRodRoleEntity;\nimport org.keycloak.models.map.storage.hotRod.user.HotRodUserConsentEntity;\n@@ -37,6 +38,9 @@ import org.keycloak.models.map.storage.hotRod.user.HotRodUserFederatedIdentityEn\nHotRodClientEntity.class,\nHotRodProtocolMapperEntity.class,\n+ // Client scopes\n+ HotRodClientScopeEntity.class,\n+\n// Groups\nHotRodGroupEntity.class,\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/resources/config/cacheConfig.xml", "new_path": "model/map-hot-rod/src/main/resources/config/cacheConfig.xml", "diff": "</indexing>\n<encoding media-type=\"application/x-protostream\"/>\n</distributed-cache>\n+ <distributed-cache name=\"client-scopes\" mode=\"SYNC\">\n+ <indexing>\n+ <indexed-entities>\n+ <indexed-entity>kc.HotRodClientScopeEntity</indexed-entity>\n+ </indexed-entities>\n+ </indexing>\n+ <encoding media-type=\"application/x-protostream\"/>\n+ </distributed-cache>\n<distributed-cache name=\"groups\" mode=\"SYNC\">\n<indexing>\n<indexed-entities>\n" }, { "change_type": "MODIFY", "old_path": "model/map-hot-rod/src/main/resources/config/infinispan.xml", "new_path": "model/map-hot-rod/src/main/resources/config/infinispan.xml", "diff": "</indexing>\n<encoding media-type=\"application/x-protostream\"/>\n</distributed-cache>\n+ <distributed-cache name=\"client-scopes\" mode=\"SYNC\">\n+ <indexing>\n+ <indexed-entities>\n+ <indexed-entity>kc.HotRodClientScopeEntity</indexed-entity>\n+ </indexed-entities>\n+ </indexing>\n+ <encoding media-type=\"application/x-protostream\"/>\n+ </distributed-cache>\n<distributed-cache name=\"groups\" mode=\"SYNC\">\n<indexing>\n<indexed-entities>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json", "new_path": "testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json", "diff": "\"username\": \"${keycloak.connectionsHotRod.username:myuser}\",\n\"password\": \"${keycloak.connectionsHotRod.password:qwer1234!}\",\n\"enableSecurity\": \"${keycloak.connectionsHotRod.enableSecurity:true}\",\n- \"reindexCaches\": \"${keycloak.connectionsHotRod.reindexCaches:clients,groups,users,roles}\"\n+ \"reindexCaches\": \"${keycloak.connectionsHotRod.reindexCaches:clients,client-scopes,groups,users,roles}\"\n}\n},\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/pom.xml", "new_path": "testsuite/integration-arquillian/tests/pom.xml", "diff": "<configuration>\n<systemPropertyVariables>\n<keycloak.client.map.storage.provider>hotrod</keycloak.client.map.storage.provider>\n+ <keycloak.clientScope.map.storage.provider>hotrod</keycloak.clientScope.map.storage.provider>\n<keycloak.group.map.storage.provider>hotrod</keycloak.group.map.storage.provider>\n<keycloak.role.map.storage.provider>hotrod</keycloak.role.map.storage.provider>\n<keycloak.user.map.storage.provider>hotrod</keycloak.user.map.storage.provider>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/main/resources/hotrod/infinispan.xml", "new_path": "testsuite/model/src/main/resources/hotrod/infinispan.xml", "diff": "</indexing>\n<encoding media-type=\"application/x-protostream\"/>\n</distributed-cache>\n+ <distributed-cache name=\"client-scopes\" mode=\"SYNC\">\n+ <indexing>\n+ <indexed-entities>\n+ <indexed-entity>kc.HotRodClientScopeEntity</indexed-entity>\n+ </indexed-entities>\n+ </indexing>\n+ <encoding media-type=\"application/x-protostream\"/>\n+ </distributed-cache>\n<distributed-cache name=\"groups\" mode=\"SYNC\">\n<indexing>\n<indexed-entities>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/ClientModelTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/ClientModelTest.java", "diff": "package org.keycloak.testsuite.model;\nimport static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.containsInAnyOrder;\n+import static org.hamcrest.Matchers.empty;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.hasSize;\nimport static org.hamcrest.Matchers.is;\n@@ -25,6 +27,7 @@ import static org.hamcrest.Matchers.notNullValue;\nimport org.junit.Test;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.ClientProvider;\n+import org.keycloak.models.ClientScopeModel;\nimport org.keycloak.models.Constants;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.RealmModel;\n@@ -32,8 +35,11 @@ import org.keycloak.models.RealmProvider;\nimport org.keycloak.models.RoleModel;\nimport org.keycloak.models.RoleProvider;\n+import java.util.LinkedList;\n+import java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n+import java.util.stream.Collectors;\n/**\n*\n@@ -213,4 +219,42 @@ public class ClientModelTest extends KeycloakModelTest {\nreturn null;\n});\n}\n+\n+ @Test\n+ public void testClientScopes() {\n+ List<String> clientScopes = new LinkedList<>();\n+ withRealm(realmId, (session, realm) -> {\n+ ClientModel client = session.clients().addClient(realm, \"myClientId\");\n+\n+ ClientScopeModel clientScope1 = session.clientScopes().addClientScope(realm, \"myClientScope1\");\n+ clientScopes.add(clientScope1.getId());\n+ ClientScopeModel clientScope2 = session.clientScopes().addClientScope(realm, \"myClientScope2\");\n+ clientScopes.add(clientScope2.getId());\n+\n+\n+ client.addClientScope(clientScope1, true);\n+ client.addClientScope(clientScope2, false);\n+\n+ return null;\n+ });\n+\n+ withRealm(realmId, (session, realm) -> {\n+ List<String> actualClientScopes = session.clientScopes().getClientScopesStream(realm).map(ClientScopeModel::getId).collect(Collectors.toList());\n+ assertThat(actualClientScopes, containsInAnyOrder(clientScopes.toArray()));\n+\n+ ClientScopeModel clientScopeById = session.clientScopes().getClientScopeById(realm, clientScopes.get(0));\n+ assertThat(clientScopeById.getId(), is(clientScopes.get(0)));\n+\n+ session.clientScopes().removeClientScopes(realm);\n+\n+ return null;\n+ });\n+\n+ withRealm(realmId, (session, realm) -> {\n+ List<ClientScopeModel> actualClientScopes = session.clientScopes().getClientScopesStream(realm).collect(Collectors.toList());\n+ assertThat(actualClientScopes, empty());\n+\n+ return null;\n+ });\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/parameters/HotRodMapStorage.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/parameters/HotRodMapStorage.java", "diff": "@@ -74,7 +74,7 @@ public class HotRodMapStorage extends KeycloakModelParameters {\npublic void updateConfig(Config cf) {\ncf.spi(AuthenticationSessionSpi.PROVIDER_ID).provider(MapRootAuthenticationSessionProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n.spi(\"client\").provider(MapClientProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, HotRodMapStorageProviderFactory.PROVIDER_ID)\n- .spi(\"clientScope\").provider(MapClientScopeProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n+ .spi(\"clientScope\").provider(MapClientScopeProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, HotRodMapStorageProviderFactory.PROVIDER_ID)\n.spi(\"group\").provider(MapGroupProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, HotRodMapStorageProviderFactory.PROVIDER_ID)\n.spi(\"realm\").provider(MapRealmProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, ConcurrentHashMapStorageProviderFactory.PROVIDER_ID)\n.spi(\"role\").provider(MapRoleProviderFactory.PROVIDER_ID).config(STORAGE_CONFIG, HotRodMapStorageProviderFactory.PROVIDER_ID)\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Hot Rod map storage: Client scope no-downtime store
339,465
09.02.2022 11:50:37
-3,600
52712d2c822471175a5c98b3084ad91ee0ffd473
ACR support in the javascript adapter Closes
[ { "change_type": "MODIFY", "old_path": "adapters/oidc/js/dist/keycloak.d.ts", "new_path": "adapters/oidc/js/dist/keycloak.d.ts", "diff": "@@ -39,6 +39,19 @@ export interface KeycloakConfig {\nclientId: string;\n}\n+export interface Acr {\n+ /**\n+ * Array of values, which will be used inside ID Token `acr` claim sent inside the `claims` parameter to Keycloak server during login.\n+ * Values should correspond to the ACR levels defined in the ACR to Loa mapping for realm or client or to the numbers (levels) inside defined\n+ * Keycloak authentication flow. See section 5.5.1 of OIDC 1.0 specification for the details.\n+ */\n+ values: string[];\n+ /**\n+ * This parameter specifies if ACR claims is considered essential or not.\n+ */\n+ essential: boolean;\n+}\n+\nexport interface KeycloakInitOptions {\n/**\n* Adds a [cryptographic nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce)\n@@ -217,6 +230,11 @@ export interface KeycloakLoginOptions {\n*/\nloginHint?: string;\n+ /**\n+ * Sets the `acr` claim of the ID token sent inside the `claims` parameter. See section 5.5.1 of the OIDC 1.0 specification.\n+ */\n+ acr?: Acr;\n+\n/**\n* Used to tell Keycloak which IDP the user wants to authenticate with.\n*/\n" }, { "change_type": "MODIFY", "old_path": "adapters/oidc/js/src/keycloak.js", "new_path": "adapters/oidc/js/src/keycloak.js", "diff": "@@ -378,6 +378,15 @@ function Keycloak (config) {\n}\n}\n+ function buildClaimsParameter(requestedAcr){\n+ var claims = {\n+ id_token: {\n+ acr: requestedAcr\n+ }\n+ }\n+ return JSON.stringify(claims);\n+ }\n+\nkc.createLoginUrl = function(options) {\nvar state = createUUID();\nvar nonce = createUUID();\n@@ -445,6 +454,11 @@ function Keycloak (config) {\nurl += '&ui_locales=' + encodeURIComponent(options.locale);\n}\n+ if (options && options.acr) {\n+ var claimsParameter = buildClaimsParameter(options.acr);\n+ url += '&claims=' + encodeURIComponent(claimsParameter);\n+ }\n+\nif (kc.pkceMethod) {\nvar codeVerifier = generateCodeVerifier(96);\ncallbackState.pkceCodeVerifier = codeVerifier;\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/javascript/JSObjectBuilder.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/javascript/JSObjectBuilder.java", "diff": "package org.keycloak.testsuite.util.javascript;\n+import java.io.IOException;\n+import java.lang.reflect.Array;\nimport java.util.HashMap;\nimport java.util.Map;\n+import org.keycloak.util.JsonSerialization;\n+\n/**\n* @author mhajas\n*/\n@@ -100,7 +104,7 @@ public class JSObjectBuilder {\n}\nprivate boolean skipQuotes(Object o) {\n- return (o instanceof Integer || o instanceof Boolean);\n+ return (o instanceof Integer || o instanceof Boolean || o instanceof JSObjectBuilder);\n}\npublic String build() {\n@@ -111,11 +115,19 @@ public class JSObjectBuilder {\n.append(option.getKey())\n.append(\" : \");\n+ if (option.getValue().getClass().isArray()) {\n+ try {\n+ argument.append(JsonSerialization.writeValueAsString(option.getValue()));\n+ } catch (IOException ioe) {\n+ throw new IllegalArgumentException(\"Not possible to serialize value of the option \" + option.getKey(), ioe);\n+ }\n+ } else {\nif (!skipQuotes(option.getValue())) argument.append(\"\\\"\");\nargument.append(option.getValue());\nif (!skipQuotes(option.getValue())) argument.append(\"\\\"\");\n+ }\ncomma = \",\";\n}\n@@ -124,5 +136,8 @@ public class JSObjectBuilder {\nreturn argument.toString();\n}\n-\n+ @Override\n+ public String toString() {\n+ return build();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/javascript/JavascriptAdapterTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/javascript/JavascriptAdapterTest.java", "diff": "@@ -9,8 +9,12 @@ import org.keycloak.OAuth2Constants;\nimport org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.common.Profile;\nimport org.keycloak.common.util.Retry;\n+import org.keycloak.common.util.UriUtils;\nimport org.keycloak.events.Details;\nimport org.keycloak.events.EventType;\n+import org.keycloak.protocol.oidc.OIDCLoginProtocol;\n+import org.keycloak.representations.ClaimsRepresentation;\n+import org.keycloak.representations.IDToken;\nimport org.keycloak.representations.idm.ClientRepresentation;\nimport org.keycloak.representations.idm.EventRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\n@@ -33,11 +37,14 @@ import org.keycloak.testsuite.util.javascript.JSObjectBuilder;\nimport org.keycloak.testsuite.util.javascript.JavascriptStateValidator;\nimport org.keycloak.testsuite.util.javascript.JavascriptTestExecutor;\nimport org.keycloak.testsuite.util.javascript.XMLHttpRequest;\n+import org.keycloak.util.JsonSerialization;\nimport org.openqa.selenium.TimeoutException;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebDriverException;\nimport org.openqa.selenium.WebElement;\n+import java.io.IOException;\n+import java.net.URL;\nimport java.util.List;\nimport java.util.Map;\n@@ -498,6 +505,52 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\n});\n}\n+ /**\n+ * Test for acr handling via {@code loginOptions}: <pre>{@code\n+ * Keycloak keycloak = new Keycloak(); keycloak.login({.... acr: { values: [\"foo\", \"bar\"], essential: false}})\n+ * }</pre>\n+ */\n+ @Test\n+ public void testAcrInLoginOptionsShouldBeConsideredByLoginUrl() {\n+ // Test when no \"acr\" option given. Claims parameter won't be passed to Keycloak server\n+ testExecutor.configure().init(defaultArguments());\n+ JSObjectBuilder loginOptions = JSObjectBuilder.create();\n+\n+ testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> {\n+ try {\n+ String queryString = new URL(driver.getCurrentUrl()).getQuery();\n+ String claimsParam = UriUtils.decodeQueryString(queryString).getFirst(OIDCLoginProtocol.CLAIMS_PARAM);\n+ Assert.assertNull(claimsParam);\n+ } catch (IOException ioe) {\n+ throw new AssertionError(ioe);\n+ }\n+ });\n+\n+ // Test given \"acr\" option will be translated into the \"claims\" parameter passed to Keycloak server\n+ jsDriver.navigate().to(testAppUrl);\n+ testExecutor.configure().init(defaultArguments());\n+\n+ JSObjectBuilder acr1 = JSObjectBuilder.create()\n+ .add(\"values\", new String[] {\"foo\", \"bar\"})\n+ .add(\"essential\", false);\n+ loginOptions = JSObjectBuilder.create().add(\"acr\", acr1);\n+\n+ testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> {\n+ try {\n+ String queryString = new URL(driver.getCurrentUrl()).getQuery();\n+ String claimsParam = UriUtils.decodeQueryString(queryString).getFirst(OIDCLoginProtocol.CLAIMS_PARAM);\n+ Assert.assertNotNull(claimsParam);\n+\n+ ClaimsRepresentation claimsRep = JsonSerialization.readValue(claimsParam, ClaimsRepresentation.class);\n+ ClaimsRepresentation.ClaimValue<String> claimValue = claimsRep.getClaimValue(IDToken.ACR, ClaimsRepresentation.ClaimContext.ID_TOKEN, String.class);\n+ Assert.assertNames(claimValue.getValues(), \"foo\", \"bar\");\n+ Assert.assertThat(claimValue.isEssential(), is(false));\n+ } catch (IOException ioe) {\n+ throw new AssertionError(ioe);\n+ }\n+ });\n+ }\n+\n@Test\npublic void testUpdateToken() {\nXMLHttpRequest request = XMLHttpRequest.create()\n" } ]
Java
Apache License 2.0
keycloak/keycloak
ACR support in the javascript adapter Closes #10154
339,618
24.02.2022 15:53:07
-3,600
c49c4f80a290e216493ef1179b3b0a64efb564af
update to quarkus 2.7.2 postgres update to 42.3.3. Did a hands-on startup performance test between 2.7.1 and 2.7.2, no change (between 3.2xx and 3.4xx seconds for start-dev with initialized db, mostly in the 3.3xx or lower 3.4xx timeframe). Also did a few smoketests Closes Closes
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<packaging>pom</packaging>\n<properties>\n- <quarkus.version>2.7.1.Final</quarkus.version>\n+ <quarkus.version>2.7.2.Final</quarkus.version>\n<!--\nPerforming a Wildfly upgrade? Run the:\n" }, { "change_type": "MODIFY", "old_path": "quarkus/pom.xml", "new_path": "quarkus/pom.xml", "diff": "<jackson.databind.version>${jackson.version}</jackson.databind.version>\n<hibernate.core.version>5.6.5.Final</hibernate.core.version>\n<mysql.driver.version>8.0.28</mysql.driver.version>\n- <postgresql.version>42.3.2</postgresql.version>\n+ <postgresql.version>42.3.3</postgresql.version>\n<microprofile-metrics-api.version>3.0.1</microprofile-metrics-api.version>\n<wildfly.common.version>1.5.4.Final-format-001</wildfly.common.version>\n<infinispan.version>13.0.5.Final</infinispan.version>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
update to quarkus 2.7.2 postgres update to 42.3.3. Did a hands-on startup performance test between 2.7.1 and 2.7.2, no change (between 3.2xx and 3.4xx seconds for start-dev with initialized db, mostly in the 3.3xx or lower 3.4xx timeframe). Also did a few smoketests Closes #10437 Closes #10282
339,487
22.02.2022 15:04:08
10,800
af7a040d54140e11bd489c1ef72320e75159a0ef
Ensure Liquibase validation is performed once per area Closes
[ { "change_type": "MODIFY", "old_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaMapStorageProviderFactory.java", "new_path": "model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/JpaMapStorageProviderFactory.java", "diff": "@@ -24,6 +24,8 @@ import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n+import java.util.Set;\n+import java.util.concurrent.ConcurrentHashMap;\nimport java.util.function.Function;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\n@@ -80,10 +82,11 @@ public class JpaMapStorageProviderFactory implements\nEnvironmentDependentProviderFactory {\npublic static final String PROVIDER_ID = \"jpa-map-storage\";\n+ private static final Logger logger = Logger.getLogger(JpaMapStorageProviderFactory.class);\nprivate volatile EntityManagerFactory emf;\n+ private final Set<Class<?>> validatedModels = ConcurrentHashMap.newKeySet();\nprivate Config.Scope config;\n- private static final Logger logger = Logger.getLogger(JpaMapStorageProviderFactory.class);\npublic final static DeepCloner CLONER = new DeepCloner.Builder()\n//client\n@@ -144,6 +147,7 @@ public class JpaMapStorageProviderFactory implements\nif (emf != null) {\nemf.close();\n}\n+ this.validatedModels.clear();\n}\nprivate void lazyInit() {\n@@ -231,8 +235,8 @@ public class JpaMapStorageProviderFactory implements\n}\npublic void validateAndUpdateSchema(KeycloakSession session, Class<?> modelType) {\n+ if (this.validatedModels.add(modelType)) {\nConnection connection = getConnection();\n-\ntry {\nif (logger.isDebugEnabled()) printOperationalInfo(connection);\n@@ -252,6 +256,7 @@ public class JpaMapStorageProviderFactory implements\n}\n}\n}\n+ }\nprivate Connection getConnection() {\ntry {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Ensure Liquibase validation is performed once per area Closes #10132
339,618
24.02.2022 18:00:32
-3,600
45c0baf84367421a780bb0a97e81b07139b3f73c
enhance container guide closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/containers.adoc", "new_path": "docs/guides/src/main/server/containers.adoc", "diff": "@@ -62,7 +62,7 @@ podman|docker build . -t prebuilt_keycloak\nTo start the image, run:\n[source, bash]\n----\n-podman|docker run --name optimized_keycloak -p 8443:8443 prebuilt_keycloak\n+podman|docker run --name optimized_keycloak -p 8443:8443 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=change_me prebuilt_keycloak\n----\nKeycloak starts in production mode, using only secured HTTPS communication, and is available on `https://localhost:8443`.\nNotice that the startup log contains the following line:\n@@ -117,4 +117,18 @@ In the example, the line `--db=postgres --features=token-exchange` sets the dat\nKeycloak then starts up and applies the configuration for the specific environment.\nThis approach significantly increases startup time and creates an image that is mutable, which is not the best practice.\n+== Provide initial admin credentials when running in a container\n+Keycloak only allows to create the initial admin user from a local network connection. This is not the case when running in a container, so you have to provide the following environment variables when you run the image:\n+\n+[source, bash]\n+----\n+# setting the admin username\n+-e KEYCLOAK_ADMIN=<admin-user-name>\n+\n+# setting the initial password\n+-e KEYCLOAK_ADMIN_PASSWORD=change_me\n+----\n+\n+Feel free to join the open https://github.com/keycloak/keycloak/discussions/8549[GitHub Discussion] around enhancements of the admin bootstrapping process.\n+\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
enhance container guide closes #10458
339,181
18.02.2022 12:01:07
18,000
7b1180856bd9a7cef49a16022f977ef2e5097929
Removing double spaces Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/configuration-production.adoc", "new_path": "docs/guides/src/main/server/configuration-production.adoc", "diff": "@@ -7,33 +7,33 @@ title=\"Configuring Keycloak for production\"\nsummary=\"Learn how to make Keycloak ready for production.\"\nincludedOptions=\"\">\n-Keycloak is used in various production environments, from on-premise deployments spanning only a few thousand users to deployments serving millions of users with secure authentication and authorization.\n+A Keycloak production environment provides secure authentication and authorization for deployments that range from on-premise deployments that support a few thousand users to deployments that serve millions of users.\n-This guide walks you through the general aspects of setting up a production ready Keycloak environment. It focusses on the main concepts and aspects instead of the actual implementation, which depends on your actual environment, be it containerized, on-premise, GitOps or Ansible. The key aspects covered in this guide apply to all of these environments.\n+This guide describes the general areas of configuration required for a production ready Keycloak environment. This information focuses on the general concepts instead of the actual implementation, which depends on your environment. The key aspects covered in this guide apply to all environments, whether it is containerized, on-premise, GitOps, or Ansible.\n-== Enabling TLS\n-Keycloak exchanges sensitive data all the time, so all communication from and to Keycloak needs to be done through a secure communication channel. For that, you must enable HTTP over TLS, or HTTPS, to prevent several attack vectors.\n+== TLS for secure communication\n+Keycloak continually exchanges sensitive data, which means that all communication to and from Keycloak requires a secure communication channel. To prevent several attack vectors, you enable HTTP over TLS, or HTTPS, for that channel.\n-The <@links.server id=\"enabletls\"/> and <@links.server id=\"outgoinghttp\"/> guides will show you the appropriate configuration to set up secure communication channels for Keycloak.\n+To configure secure communication channels for Keycloak, see the <@links.server id=\"enabletls\"/> and <@links.server id=\"outgoinghttp\"/> guides.\n-== Setting the hostname for Keycloak\n-Keycloak instances in production usually run in a private network, but Keycloak needs to expose different public facing endpoints to communicate with applications that will be secured.\n+== The hostname for Keycloak\n+In a production environment, Keycloak instances usually run in a private network, but Keycloak needs to expose certain public facing endpoints to communicate with the applications to be secured.\n-Learn in the <@links.server id=\"hostname\"/> guide what the different endpoint categories are and how to configure the public hostname for them, depending on your specific environment.\n+For details on the endpoint categories and instructions on how to configure the public hostname for them, see the <@links.server id=\"hostname\"/> guide.\n-== Configure a reverse proxy\n-Apart from <<Setting the hostname for Keycloak>>, production environments usually use a reverse proxy / load balancer component to separate and unify access to the companies network. Using such a component is recommended for Keycloak production deployments.\n+== Reverse proxy in a distributed environment\n+Apart from <<Setting the hostname for Keycloak>>, production environments usually include a reverse proxy / load balancer component. It separates and unifies access to the network used by your company or organization. For a Keycloak production environment, this component is recommended.\n-In the <@links.server id=\"reverseproxy\"/> guide you can find the available proxy communication modes in Keycloak and how to configure them. There's also a recommendation which paths should not be exposed to the public at all, and which paths need to be exposed for Keycloak to be able to secure your applications.\n+For details on configuring proxy communication modes in Keycloak, see the <@links.server id=\"reverseproxy\"/> guide. That guide also recommends which paths should be hidden from public access and which paths should be exposed so that Keycloak can secure your applications.\n-== Configure a production grade database\n-The database used by Keycloak is crucial for the overall performance, availability, reliability and integrity of Keycloak. In the <@links.server id=\"db\"/> guide you can find the supported database vendors and how to configure Keycloak to use them.\n+== Production grade database\n+The database used by Keycloak is crucial for the overall performance, availability, reliability and integrity of Keycloak. For details on how to configure a supported database, see the <@links.server id=\"db\"/> guide.\n-== Run Keycloak in a cluster\n-You'd not want every login to fail when your Keycloak instance goes down, so typical production deployments consist of two or more Keycloak instances.\n+== Support for Keycloak in a cluster\n+To ensure that users can continue to log in when a Keycloak instance goes down, a typical production environment contains two or more Keycloak instances.\n-Keycloak uses JGroups and Infinispan under the covers to provide a reliable, HA-ready stack to run in a clustered scenario. When deployed to a cluster the embedded Infinispan server communication should be secured. Either by enabling authentication and encryption, or through isolating the network used for cluster communication.\n+Keycloak runs on top of JGroups and Infinispan, which provide a reliable, high-availability stack for a clustered scenario. When deployed to a cluster, the embedded Infinispan server communication should be secured. You secure this communication either by enabling authentication and encryption or by isolating the network used for cluster communication.\n-To find out more about using multiple nodes, the different caches and the right stack for your environment, see the <@links.server id=\"caching\"/> guide.\n+To find out more about using multiple nodes, the different caches and an appropriate stack for your environment, see the <@links.server id=\"caching\"/> guide.\n</@tmpl.guide>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Removing double spaces Closes #10309
339,711
25.02.2022 17:51:34
0
c93fee0c68159ab30fa6dd13847c54c7356e15b8
Update sha256 import to be default import This should fix the "Failed to compile. ./node_modules/keycloak-js/dist/keycloak.mjs Can't import the named export 'sha256' from non EcmaScript module (only default export is available)" error. Closes
[ { "change_type": "MODIFY", "old_path": "adapters/oidc/js/src/keycloak.js", "new_path": "adapters/oidc/js/src/keycloak.js", "diff": "* limitations under the License.\n*/\nimport base64 from 'base64-js';\n-import { sha256 } from 'js-sha256';\n+import sha256 from 'js-sha256';\nif (typeof Promise === 'undefined') {\nthrow Error('Keycloak requires an environment that supports Promises. Make sure that you include the appropriate polyfill.');\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Update sha256 import to be default import (#10468) This should fix the "Failed to compile. ./node_modules/keycloak-js/dist/keycloak.mjs Can't import the named export 'sha256' from non EcmaScript module (only default export is available)" error. Closes #10314
339,588
14.02.2022 16:01:01
-3,600
74695c02423345dab892a0808bf9203c3f92af7c
Add annotation to PathCacheConfig.lifespan. Closes
[ { "change_type": "MODIFY", "old_path": "core/src/main/java/org/keycloak/representations/adapters/config/PolicyEnforcerConfig.java", "new_path": "core/src/main/java/org/keycloak/representations/adapters/config/PolicyEnforcerConfig.java", "diff": "@@ -329,6 +329,7 @@ public class PolicyEnforcerConfig {\n@JsonProperty(\"max-entries\")\nint maxEntries = 1000;\n+ @JsonProperty(\"lifespan\")\nlong lifespan = 30000;\npublic int getMaxEntries() {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add @JsonProperty annotation to PathCacheConfig.lifespan. Closes #9756.
339,425
02.02.2022 14:53:33
-3,600
76101e359181b0e04004f59eb09d88b544fddbbe
[fixes - Get scopeIds from the AuthorizationRequestContext instead of session if DYNAMIC_SCOPES are enabled Add a test to make sure ProtocolMappers run with Dynamic Scopes Change the way we create the DefaultClientSessionContext with respect to OAuth2 scopes, and standardize the way we obtain them from the parameter
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "diff": "@@ -29,6 +29,7 @@ import org.keycloak.broker.oidc.OIDCIdentityProvider;\nimport org.keycloak.broker.provider.IdentityBrokerException;\nimport org.keycloak.cluster.ClusterProvider;\nimport org.keycloak.common.ClientConnection;\n+import org.keycloak.common.Profile;\nimport org.keycloak.common.VerificationException;\nimport org.keycloak.common.util.Time;\nimport org.keycloak.crypto.HashProvider;\n@@ -76,6 +77,7 @@ import org.keycloak.services.managers.AuthenticationSessionManager;\nimport org.keycloak.services.managers.UserSessionCrossDCManager;\nimport org.keycloak.services.managers.UserSessionManager;\nimport org.keycloak.services.resources.IdentityBrokerService;\n+import org.keycloak.services.util.AuthorizationContextUtil;\nimport org.keycloak.services.util.DefaultClientSessionContext;\nimport org.keycloak.services.util.MtlsHoKTokenUtil;\nimport org.keycloak.sessions.AuthenticationSessionModel;\n@@ -544,7 +546,14 @@ public class TokenManager {\nclientSession.setRedirectUri(authSession.getRedirectUri());\nclientSession.setProtocol(authSession.getProtocol());\n- Set<String> clientScopeIds = authSession.getClientScopes();\n+ Set<String> clientScopeIds;\n+ if (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n+ clientScopeIds = AuthorizationContextUtil.getClientScopesStreamFromAuthorizationRequestContextWithClient(session, authSession.getClientNote(OAuth2Constants.SCOPE))\n+ .map(ClientScopeModel::getId)\n+ .collect(Collectors.toSet());\n+ } else {\n+ clientScopeIds = authSession.getClientScopes();\n+ }\nMap<String, String> transferredNotes = authSession.getClientNotes();\nfor (Map.Entry<String, String> entry : transferredNotes.entrySet()) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java", "diff": "@@ -424,7 +424,7 @@ public class TokenEndpoint {\nthrow new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, \"Client no longer has requested consent from user\", Response.Status.BAD_REQUEST);\n}\n- ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndClientScopes(clientSession, clientScopesSupplier.get(), session);\n+ ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndScopeParameter(clientSession, scopeParam, session);\n// Set nonce as an attribute in the ClientSessionContext. Will be used for the token generation\nclientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, codeData.getNonce());\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/ciba/CibaGrantType.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/ciba/CibaGrantType.java", "diff": "@@ -212,7 +212,7 @@ public class CibaGrantType {\n}\nClientSessionContext clientSessionCtx = DefaultClientSessionContext\n- .fromClientSessionAndClientScopes(userSession.getAuthenticatedClientSessionByClient(client.getId()), TokenManager.getRequestedClientScopes(scopeParam, client), session);\n+ .fromClientSessionAndScopeParameter(userSession.getAuthenticatedClientSessionByClient(client.getId()), scopeParam, session);\nint authTime = Time.currentTime();\nuserSession.setNote(AuthenticationManager.AUTH_TIME, String.valueOf(authTime));\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/device/DeviceGrantType.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/grants/device/DeviceGrantType.java", "diff": "@@ -292,8 +292,8 @@ public class DeviceGrantType {\n\"Client no longer has requested consent from user\", Response.Status.BAD_REQUEST);\n}\n- ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndClientScopes(clientSession,\n- TokenManager.getRequestedClientScopes(scopeParam, client), session);\n+ ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndScopeParameter(clientSession,\n+ scopeParam, session);\n// Set nonce as an attribute in the ClientSessionContext. Will be used for the token generation\nclientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, deviceCodeModel.getNonce());\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java", "new_path": "services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java", "diff": "@@ -1192,9 +1192,7 @@ public class AuthenticationManager {\n//if Dynamic Scopes are enabled, get the scopes from the AuthorizationRequestContext, passing the session and scopes as parameters\n// then concat a Stream with the ClientModel, as it's discarded in the getAuthorizationRequestContext method\nif (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n- return Stream.concat(AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, authSession.getClientNote(OAuth2Constants.SCOPE))\n- .getAuthorizationDetailEntries().stream(),\n- Collections.singletonList(new AuthorizationDetails(session.getContext().getClient())).stream());\n+ return AuthorizationContextUtil.getAuthorizationRequestsStreamFromScopesWithClient(session, authSession.getClientNote(OAuth2Constants.SCOPE));\n}\n// if dynamic scopes are not enabled, we retain the old behaviour, but the ClientScopes will be wrapped in\n// AuthorizationRequest objects to standardize the code handling these.\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/util/AuthorizationContextUtil.java", "new_path": "services/src/main/java/org/keycloak/services/util/AuthorizationContextUtil.java", "diff": "+/*\n+ * Copyright 2022 Red Hat, Inc. and/or its affiliates\n+ * and other contributors as indicated by the @author tags.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\npackage org.keycloak.services.util;\nimport org.keycloak.common.Profile;\n+import org.keycloak.models.ClientScopeModel;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.protocol.oidc.rar.AuthorizationRequestParserProvider;\nimport org.keycloak.protocol.oidc.rar.parsers.ClientScopeAuthorizationRequestParserProviderFactory;\n+import org.keycloak.rar.AuthorizationDetails;\nimport org.keycloak.rar.AuthorizationRequestContext;\n+import org.keycloak.rar.AuthorizationRequestSource;\n+import java.util.stream.Stream;\n+\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Daniel Gozalo</a>\n+ * Util class to unify a way to obtain the {@link AuthorizationRequestContext}.\n+ * <p>\n+ * As it can be obtained statically from just the OAuth2 scopes parameter, it can be easily referenced from almost anywhere.\n+ */\npublic class AuthorizationContextUtil {\n+ /**\n+ * Base function to obtain a bare AuthorizationRequestContext with just OAuth2 Scopes\n+ * @param session\n+ * @param scope\n+ * @return an {@link AuthorizationRequestContext} with scope entries\n+ */\npublic static AuthorizationRequestContext getAuthorizationRequestContextFromScopes(KeycloakSession session, String scope) {\nif (!Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\nthrow new RuntimeException(\"The Dynamic Scopes feature is not enabled and the AuthorizationRequestContext hasn't been generated\");\n@@ -23,4 +57,38 @@ public class AuthorizationContextUtil {\nreturn clientScopeParser.parseScopes(scope);\n}\n+ /**\n+ * An extension of {@link AuthorizationContextUtil#getAuthorizationRequestContextFromScopes} that appends the current context's client\n+ * @param session\n+ * @param scope\n+ * @return an {@link AuthorizationRequestContext} with scope entries and a ClientModel\n+ */\n+ public static AuthorizationRequestContext getAuthorizationRequestContextFromScopesWithClient(KeycloakSession session, String scope) {\n+ AuthorizationRequestContext authorizationRequestContext = getAuthorizationRequestContextFromScopes(session, scope);\n+ authorizationRequestContext.getAuthorizationDetailEntries().add(new AuthorizationDetails(session.getContext().getClient()));\n+ return authorizationRequestContext;\n+ }\n+\n+ /**\n+ * An extension of {@link AuthorizationContextUtil#getAuthorizationRequestContextFromScopesWithClient)} that returns the list as a Stream\n+ * @param session\n+ * @param scope\n+ * @return a Stream of {@link AuthorizationDetails} containing a ClientModel\n+ */\n+ public static Stream<AuthorizationDetails> getAuthorizationRequestsStreamFromScopesWithClient(KeycloakSession session, String scope) {\n+ AuthorizationRequestContext authorizationRequestContext = getAuthorizationRequestContextFromScopesWithClient(session, scope);\n+ return authorizationRequestContext.getAuthorizationDetailEntries().stream();\n+ }\n+\n+ /**\n+ * Helper method to return a Stream of all the {@link ClientScopeModel} in the current {@link AuthorizationRequestContext}\n+ * @param session\n+ * @param scope\n+ * @return see description\n+ */\n+ public static Stream<ClientScopeModel> getClientScopesStreamFromAuthorizationRequestContextWithClient(KeycloakSession session, String scope) {\n+ return getAuthorizationRequestContextFromScopesWithClient(session, scope).getAuthorizationDetailEntries().stream()\n+ .filter(authorizationDetails -> authorizationDetails.getSource() == AuthorizationRequestSource.SCOPE)\n+ .map(AuthorizationDetails::getClientScope);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/util/DefaultClientSessionContext.java", "new_path": "services/src/main/java/org/keycloak/services/util/DefaultClientSessionContext.java", "diff": "@@ -71,8 +71,8 @@ public class DefaultClientSessionContext implements ClientSessionContext {\nprivate Map<String, Object> attributes = new HashMap<>();\nprivate DefaultClientSessionContext(AuthenticatedClientSessionModel clientSession, Set<String> clientScopeIds, KeycloakSession session) {\n- this.clientSession = clientSession;\nthis.clientScopeIds = clientScopeIds;\n+ this.clientSession = clientSession;\nthis.session = session;\n}\n@@ -86,7 +86,12 @@ public class DefaultClientSessionContext implements ClientSessionContext {\npublic static DefaultClientSessionContext fromClientSessionAndScopeParameter(AuthenticatedClientSessionModel clientSession, String scopeParam, KeycloakSession session) {\n- Stream<ClientScopeModel> requestedClientScopes = TokenManager.getRequestedClientScopes(scopeParam, clientSession.getClient());\n+ Stream<ClientScopeModel> requestedClientScopes;\n+ if (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {\n+ requestedClientScopes = AuthorizationContextUtil.getClientScopesStreamFromAuthorizationRequestContextWithClient(session, scopeParam);\n+ } else {\n+ requestedClientScopes = TokenManager.getRequestedClientScopes(scopeParam, clientSession.getClient());\n+ }\nreturn fromClientSessionAndClientScopes(clientSession, requestedClientScopes, session);\n}\n@@ -96,7 +101,10 @@ public class DefaultClientSessionContext implements ClientSessionContext {\n}\n- public static DefaultClientSessionContext fromClientSessionAndClientScopes(AuthenticatedClientSessionModel clientSession,\n+ // in order to standardize the way we create this object and with that data, it's better to compute the client scopes internally instead of relying on external sources\n+ // i.e: the TokenManager.getRequestedClientScopes was being called in many places to obtain the ClientScopeModel stream.\n+ // by changing this method to private, we'll only call it in this class, while also having a single place to put the DYNAMIC_SCOPES feature flag condition\n+ private static DefaultClientSessionContext fromClientSessionAndClientScopes(AuthenticatedClientSessionModel clientSession,\nStream<ClientScopeModel> clientScopes,\nKeycloakSession session) {\nSet<String> clientScopeIds = clientScopes.map(ClientScopeModel::getId).collect(Collectors.toSet());\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OIDCProtocolMappersTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OIDCProtocolMappersTest.java", "diff": "@@ -30,6 +30,7 @@ import org.keycloak.common.Profile;\nimport org.keycloak.common.util.UriUtils;\nimport org.keycloak.jose.jws.JWSInput;\nimport org.keycloak.models.AccountRoles;\n+import org.keycloak.models.ClientScopeModel;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;\nimport org.keycloak.protocol.oidc.mappers.AddressMapper;\n@@ -65,6 +66,7 @@ import javax.ws.rs.core.Response;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Arrays;\nimport java.util.Collection;\n+import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n@@ -1268,6 +1270,44 @@ public class OIDCProtocolMappersTest extends AbstractKeycloakTest {\n}\n}\n+ @Test\n+ @EnableFeature(value = Profile.Feature.DYNAMIC_SCOPES, skipRestart = true)\n+ public void executeTokenMappersOnDynamicScopes() {\n+ ClientResource clientResource = findClientResourceByClientId(adminClient.realm(\"test\"), \"test-app\");\n+ ClientScopeRepresentation scopeRep = new ClientScopeRepresentation();\n+ scopeRep.setName(\"dyn-scope-with-mapper\");\n+ scopeRep.setProtocol(\"openid-connect\");\n+ scopeRep.setAttributes(new HashMap<String, String>() {{\n+ put(ClientScopeModel.IS_DYNAMIC_SCOPE, \"true\");\n+ put(ClientScopeModel.DYNAMIC_SCOPE_REGEXP, \"dyn-scope-with-mapper:*\");\n+ }});\n+ // create the attribute mapper\n+ ProtocolMapperRepresentation protocolMapperRepresentation = createHardcodedClaim(\"dynamic-scope-hardcoded-mapper\", \"hardcoded-foo\", \"hardcoded-bar\", \"String\", true, true);\n+ scopeRep.setProtocolMappers(Collections.singletonList(protocolMapperRepresentation));\n+\n+ try (Response resp = adminClient.realm(\"test\").clientScopes().create(scopeRep)) {\n+ assertEquals(201, resp.getStatus());\n+ String clientScopeId = ApiUtil.getCreatedId(resp);\n+ getCleanup().addClientScopeId(clientScopeId);\n+ clientResource.addOptionalClientScope(clientScopeId);\n+ }\n+\n+ oauth.scope(\"openid dyn-scope-with-mapper:value\");\n+ OAuthClient.AccessTokenResponse response = browserLogin(\"password\", \"test-user@localhost\", \"password\");\n+ IDToken idToken = oauth.verifyIDToken(response.getIdToken());\n+ AccessToken accessToken = oauth.verifyToken(response.getAccessToken());\n+\n+ assertNotNull(idToken.getOtherClaims());\n+ assertNotNull(idToken.getOtherClaims().get(\"hardcoded-foo\"));\n+ assertTrue(idToken.getOtherClaims().get(\"hardcoded-foo\") instanceof String);\n+ assertEquals(\"hardcoded-bar\", idToken.getOtherClaims().get(\"hardcoded-foo\"));\n+\n+ assertNotNull(accessToken.getOtherClaims());\n+ assertNotNull(accessToken.getOtherClaims().get(\"hardcoded-foo\"));\n+ assertTrue(accessToken.getOtherClaims().get(\"hardcoded-foo\") instanceof String);\n+ assertEquals(\"hardcoded-bar\", accessToken.getOtherClaims().get(\"hardcoded-foo\"));\n+ }\n+\nprivate void assertRoles(List<String> actualRoleList, String ...expectedRoles){\nAssert.assertNames(actualRoleList, expectedRoles);\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[fixes #9225] - Get scopeIds from the AuthorizationRequestContext instead of session if DYNAMIC_SCOPES are enabled Add a test to make sure ProtocolMappers run with Dynamic Scopes Change the way we create the DefaultClientSessionContext with respect to OAuth2 scopes, and standardize the way we obtain them from the parameter
339,535
11.02.2022 17:43:42
-3,600
91d37b5686fd05850cf474920a7ade76f443f9fd
Single offlineSession imported in Infinispan with correctly calculated lifespan and maxIdle parameters Close
[ { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProvider.java", "new_path": "model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProvider.java", "diff": "@@ -20,6 +20,7 @@ package org.keycloak.models.sessions.infinispan;\nimport org.infinispan.Cache;\nimport org.infinispan.client.hotrod.RemoteCache;\nimport org.infinispan.client.hotrod.exceptions.HotRodClientException;\n+import org.infinispan.commons.api.BasicCache;\nimport org.infinispan.context.Flag;\nimport org.infinispan.stream.CacheCollectors;\nimport org.jboss.logging.Logger;\n@@ -42,6 +43,7 @@ import org.keycloak.models.session.UserSessionPersisterProvider;\nimport org.keycloak.models.sessions.infinispan.changes.Tasks;\nimport org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStore;\nimport org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStore;\n+import org.keycloak.models.sessions.infinispan.entities.SessionEntity;\nimport org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheInvoker;\nimport org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper;\nimport org.keycloak.models.sessions.infinispan.changes.InfinispanChangelogBasedTransaction;\n@@ -72,7 +74,9 @@ import java.util.Set;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.Future;\n+import java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n+import java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n@@ -848,7 +852,15 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\n// Directly put all entities to the infinispan cache\nCache<String, SessionEntityWrapper<UserSessionEntity>> cache = CacheDecorators.skipCacheLoaders(getCache(offline));\n+\n+ boolean importWithExpiration = sessionsById.size() == 1;\n+ if (importWithExpiration) {\n+ importSessionsWithExpiration(sessionsById, cache,\n+ offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs,\n+ offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);\n+ } else {\ncache.putAll(sessionsById);\n+ }\n// put all entities to the remoteCache (if exists)\nRemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);\n@@ -857,6 +869,11 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\n.map(SessionEntityWrapper::forTransport)\n.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));\n+ if (importWithExpiration) {\n+ importSessionsWithExpiration(sessionsByIdForTransport, remoteCache,\n+ offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs,\n+ offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);\n+ } else {\nRetry.executeWithBackoff((int iteration) -> {\ntry {\n@@ -873,12 +890,19 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\n}, 10, 10);\n}\n+ }\n// Import client sessions\nCache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessCache = offline ? offlineClientSessionCache : clientSessionCache;\nclientSessCache = CacheDecorators.skipCacheLoaders(clientSessCache);\n+ if (importWithExpiration) {\n+ importSessionsWithExpiration(clientSessionsById, clientSessCache,\n+ offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs,\n+ offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);\n+ } else {\nclientSessCache.putAll(clientSessionsById);\n+ }\n// put all entities to the remoteCache (if exists)\nRemoteCache remoteCacheClientSessions = InfinispanUtil.getRemoteCache(clientSessCache);\n@@ -887,6 +911,11 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\n.map(SessionEntityWrapper::forTransport)\n.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));\n+ if (importWithExpiration) {\n+ importSessionsWithExpiration(sessionsByIdForTransport, remoteCacheClientSessions,\n+ offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs,\n+ offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);\n+ } else {\nRetry.executeWithBackoff((int iteration) -> {\ntry {\n@@ -904,7 +933,42 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {\n}, 10, 10);\n}\n}\n+ }\n+\n+ private <T extends SessionEntity> void importSessionsWithExpiration(Map<? extends Object, SessionEntityWrapper<T>> sessionsById,\n+ BasicCache cache, BiFunction<RealmModel, T, Long> lifespanMsCalculator,\n+ BiFunction<RealmModel, T, Long> maxIdleTimeMsCalculator) {\n+ sessionsById.forEach((id, sessionEntityWrapper) -> {\n+ T sessionEntity = sessionEntityWrapper.getEntity();\n+ RealmModel currentRealm = session.realms().getRealm(sessionEntity.getRealmId());\n+ long lifespan = lifespanMsCalculator.apply(currentRealm, sessionEntity);\n+ long maxIdle = maxIdleTimeMsCalculator.apply(currentRealm, sessionEntity);\n+\n+ if(lifespan != SessionTimeouts.ENTRY_EXPIRED_FLAG\n+ && maxIdle != SessionTimeouts.ENTRY_EXPIRED_FLAG ) {\n+ if (cache instanceof RemoteCache) {\n+ Retry.executeWithBackoff((int iteration) -> {\n+\n+ try {\n+ cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);\n+ } catch (HotRodClientException re) {\n+ if (log.isDebugEnabled()) {\n+ log.debugf(re, \"Failed to put import %d sessions to remoteCache. Iteration '%s'. Will try to retry the task\",\n+ sessionsById.size(), iteration);\n+ }\n+\n+ // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.\n+ throw re;\n+ }\n+\n+ }, 10, 10);\n+ } else {\n+ cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);\n+ }\n+ }\n+ });\n+ }\n// Imports just userSession without it's clientSessions\nprotected UserSessionAdapter importUserSession(UserSessionModel userSession, boolean offline) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Single offlineSession imported in Infinispan with correctly calculated lifespan and maxIdle parameters Close #8776
339,546
01.03.2022 13:43:49
-3,600
700ceb77ec2acd977c2adefbc9509c6e12a3611a
Removal of invalid(depricated) SpringBootTest Closes
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/springboot-tests/src/test/java/org/keycloak/testsuite/springboot/AccountLinkSpringBootTest.java", "new_path": "testsuite/integration-arquillian/tests/other/springboot-tests/src/test/java/org/keycloak/testsuite/springboot/AccountLinkSpringBootTest.java", "diff": "@@ -492,56 +492,6 @@ public class AccountLinkSpringBootTest extends AbstractSpringBootTest {\n}\n}\n- @Test\n- public void testAccountNotLinkedAutomatically() throws Exception {\n- RealmResource realm = adminClient.realms().realm(REALM_NAME);\n- List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();\n- assertThat(links, is(empty()));\n-\n- // Login to account mgmt first\n- profilePage.open(REALM_NAME);\n- WaitUtils.waitForPageToLoad();\n-\n- assertCurrentUrlStartsWith(testRealmLoginPage);\n- testRealmLoginPage.form().login(CHILD_USERNAME_1, CHILD_PASSWORD_1);\n- profilePage.assertCurrent();\n-\n- // Now in another tab, open login screen with \"prompt=login\" . Login screen will be displayed even if I have SSO cookie\n- UriBuilder linkBuilder = UriBuilder.fromUri(LINKING_URL);\n- String linkUrl = linkBuilder.clone()\n- .queryParam(OIDCLoginProtocol.PROMPT_PARAM, OIDCLoginProtocol.PROMPT_VALUE_LOGIN)\n- .build().toString();\n-\n- navigateTo(linkUrl);\n- assertCurrentUrlStartsWith(testRealmLoginPage);\n-\n- loginPage.clickSocial(PARENT_REALM);\n-\n- testRealmLoginPage.setAuthRealm(PARENT_REALM);\n- assertCurrentUrlStartsWith(testRealmLoginPage);\n- testRealmLoginPage.form().login(PARENT_USERNAME, PARENT_PASSWORD);\n- testRealmLoginPage.setAuthRealm(REALM_NAME);\n-\n- // Test I was not automatically linked.\n- links = realm.users().get(childUserId).getFederatedIdentity();\n- assertThat(links, is(empty()));\n-\n- loginUpdateProfilePage.assertCurrent();\n- loginUpdateProfilePage.update(\"Joe\", \"Doe\", \"[email protected]\");\n-\n- errorPage.assertCurrent();\n-\n- assertThat(errorPage.getError(), is(equalTo(\"You are already authenticated as different user '\"\n- + CHILD_USERNAME_1\n- + \"' in this session. Please sign out first.\")));\n-\n- logoutAll();\n-\n- // Remove newly created user\n- String newUserId = ApiUtil.findUserByUsername(realm, PARENT_USERNAME).getId();\n- getCleanup(REALM_NAME).addUserId(newUserId);\n- }\n-\n@Test\npublic void testAccountLinkingExpired() throws Exception {\nRealmResource realm = adminClient.realms().realm(REALM_NAME);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Removal of invalid(depricated) SpringBootTest Closes #10218
339,511
03.03.2022 15:32:08
-32,400
92f6c753281079624c08583bd91dba3c474d833f
Nonce parameter should be required in authorizationEndpoint only when "id_token" is included in response_type Closes
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpointChecker.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpointChecker.java", "diff": "@@ -227,7 +227,7 @@ public class AuthorizationEndpointChecker {\nreturn;\n}\n- if (parsedResponseType.isImplicitOrHybridFlow() && request.getNonce() == null) {\n+ if (parsedResponseType.hasResponseType(OIDCResponseType.ID_TOKEN) && request.getNonce() == null) {\nServicesLogger.LOGGER.missingParameter(OIDCLoginProtocol.NONCE_PARAM);\nevent.error(Errors.INVALID_REQUEST);\nthrow new AuthorizationCheckException(Response.Status.BAD_REQUEST, OAuthErrorException.INVALID_REQUEST, \"Missing parameter: nonce\");\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/AbstractOIDCResponseTypeTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/AbstractOIDCResponseTypeTest.java", "diff": "@@ -131,6 +131,9 @@ public abstract class AbstractOIDCResponseTypeTest extends AbstractTestRealmKeyc\nevents.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent();\n}\n+ protected void validateNonceNotUsedSuccessExpected() {\n+ loginUser(null);\n+ }\nprotected void validateNonceNotUsedErrorExpected() {\noauth.nonce(null);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeTokenTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeTokenTest.java", "diff": "@@ -76,7 +76,7 @@ public class OIDCHybridResponseTypeCodeTokenTest extends AbstractOIDCResponseTyp\n@Test\npublic void nonceNotUsedErrorExpected() {\n- super.validateNonceNotUsedErrorExpected();\n+ super.validateNonceNotUsedSuccessExpected();\n}\n@Test\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Nonce parameter should be required in authorizationEndpoint only when "id_token" is included in response_type Closes #10143
339,410
17.02.2022 11:22:17
-3,600
ebfc24d6c105971f00f86d1c96fc0dc2aed45bf9
Ensure that Infinispan shutdowns correctly at the end of the tests. Report any exceptions within another thread as a test failure. Adding additional information like a thread dump when it doesn't shutdown as expected. Closes
[ { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanClusterProviderFactory.java", "new_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanClusterProviderFactory.java", "diff": "@@ -201,6 +201,7 @@ public class InfinispanClusterProviderFactory implements ClusterProviderFactory\n// Use separate thread to avoid potential deadlock\nlocalExecutor.execute(() -> {\n+ try {\nEmbeddedCacheManager cacheManager = workCache.getCacheManager();\nTransport transport = cacheManager.getTransport();\n@@ -224,6 +225,9 @@ public class InfinispanClusterProviderFactory implements ClusterProviderFactory\nworkCache.entrySet().removeIf(new LockEntryPredicate(removedNodesAddresses));\n}\n}\n+ } catch (Throwable t) {\n+ logger.error(\"caught exception in ViewChangeListener\", t);\n+ }\n});\n}\n" }, { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanNotificationsManager.java", "new_path": "model/infinispan/src/main/java/org/keycloak/cluster/infinispan/InfinispanNotificationsManager.java", "diff": "@@ -254,7 +254,8 @@ public class InfinispanNotificationsManager {\n});\n} catch (RejectedExecutionException ree) {\n- logger.errorf(\"Rejected submitting of the event for key: %s. Value: %s, Server going to shutdown or pool exhausted. Pool: %s\", key, workCache.get(key), listenersExecutor.toString());\n+ // avoid touching the cache when creating a log message to avoid a deadlock in Infinispan 12.1.7.Final\n+ logger.errorf(\"Rejected submitting of the event for key: %s. Server going to shutdown or pool exhausted. Pool: %s\", key, listenersExecutor.toString());\nthrow ree;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/pom.xml", "new_path": "testsuite/model/pom.xml", "diff": "<log4j.configuration>file:${project.build.directory}/test-classes/log4j.properties</log4j.configuration> <!-- for the logging to properly work with tests in the 'other' module -->\n<keycloak.profile.feature.map_storage>${keycloak.profile.feature.map_storage}</keycloak.profile.feature.map_storage>\n<keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>${keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase}</keycloak.userSessions.infinispan.preloadOfflineSessionsFromDatabase>\n+ <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>\n+ <org.jboss.logging.provider>log4j</org.jboss.logging.provider>\n</systemPropertyVariables>\n</configuration>\n</plugin>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/KeycloakModelTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/KeycloakModelTest.java", "diff": "*/\npackage org.keycloak.testsuite.model;\n+import org.infinispan.commons.CacheConfigurationException;\n+import org.infinispan.manager.EmbeddedCacheManagerStartupException;\n+import org.junit.Assert;\nimport org.keycloak.Config.Scope;\nimport org.keycloak.authorization.AuthorizationSpi;\nimport org.keycloak.authorization.DefaultAuthorizationProviderFactory;\n@@ -49,18 +52,29 @@ import org.keycloak.services.DefaultComponentFactoryProviderFactory;\nimport org.keycloak.services.DefaultKeycloakSessionFactory;\nimport org.keycloak.timer.TimerSpi;\nimport com.google.common.collect.ImmutableSet;\n+\n+import java.lang.management.LockInfo;\n+import java.lang.management.ManagementFactory;\n+import java.lang.management.ThreadInfo;\nimport java.util.Arrays;\nimport java.util.Iterator;\n+import java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\n+import java.util.concurrent.CountDownLatch;\n+import java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n+import java.util.concurrent.Future;\nimport java.util.concurrent.Semaphore;\n+import java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.TimeUnit;\n+import java.util.concurrent.TimeoutException;\n+import java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.BiConsumer;\n@@ -155,7 +169,7 @@ public abstract class KeycloakModelTest {\nif (getFactory().getProviderFactory(providerClass) == null) {\nreturn new Statement() {\n@Override\n- public void evaluate() throws Throwable {\n+ public void evaluate() {\nthrow new AssumptionViolatedException(\"Provider must exist: \" + providerClass);\n}\n};\n@@ -165,7 +179,7 @@ public abstract class KeycloakModelTest {\nif (notFoundAny) {\nreturn new Statement() {\n@Override\n- public void evaluate() throws Throwable {\n+ public void evaluate() {\nthrow new AssumptionViolatedException(\"Provider must exist: \" + providerClass + \" one of [\" + String.join(\",\", only) + \"]\");\n}\n};\n@@ -322,48 +336,139 @@ public abstract class KeycloakModelTest {\n* Runs the given {@code task} in {@code numThreads} parallel threads, each thread operating\n* in the context of a fresh {@link KeycloakSessionFactory} independent of each other thread.\n*\n+ * Will throw an exception when the thread throws an exception or if the thread doesn't complete in time.\n+ *\n* @see #inIndependentFactory\n*\n- * @param numThreads\n- * @param timeoutSeconds\n- * @param task\n- * @throws InterruptedException\n*/\npublic static void inIndependentFactories(int numThreads, int timeoutSeconds, Runnable task) throws InterruptedException {\n- ExecutorService es = Executors.newFixedThreadPool(numThreads);\n+ enabledContentionMonitoring();\n+ // memorize threads created to be able to retrieve their stacktrace later if they don't terminate\n+ LinkedList<Thread> threads = new LinkedList<>();\n+ ExecutorService es = Executors.newFixedThreadPool(numThreads, new ThreadFactory() {\n+ final ThreadFactory tf = Executors.defaultThreadFactory();\n+ @Override\n+ public Thread newThread(Runnable r) {\n+ {\n+ Thread thread = tf.newThread(r);\n+ threads.add(thread);\n+ return thread;\n+ }\n+ }\n+ });\ntry {\n/*\nworkaround for Infinispan 12.1.7.Final to prevent an internal Infinispan NullPointerException\n- when multiple nodes tried to join at the same time by starting them sequentially with 1 sec delay.\n+ when multiple nodes tried to join at the same time by starting them sequentially,\n+ although that does not catch 100% of all occurrences.\nAlready fixed in Infinispan 13.\nhttps://issues.redhat.com/browse/ISPN-13231\n*/\nSemaphore sem = new Semaphore(1);\n+ CountDownLatch start = new CountDownLatch(numThreads);\n+ CountDownLatch stop = new CountDownLatch(numThreads);\nCallable<?> independentTask = () -> {\n+ AtomicBoolean locked = new AtomicBoolean(false);\ntry {\nsem.acquire();\n- return inIndependentFactory(() -> {\n- Thread.sleep(1000);\n+ locked.set(true);\n+ Object val = inIndependentFactory(() -> {\nsem.release();\n+ locked.set(false);\n+\n+ // use the latch to ensure that all caches are online while the transaction below runs to avoid a RemoteException\n+ start.countDown();\n+ start.await();\n+\n+ try {\ntask.run();\n+\n+ // use the latch to ensure that all caches are online while the transaction above runs to avoid a RemoteException\n+ // otherwise might fail with \"Cannot wire or start components while the registry is not running\" during shutdown\n+ // https://issues.redhat.com/browse/ISPN-9761\n+ } finally {\n+ stop.countDown();\n+ }\n+ stop.await();\n+\n+ sem.acquire();\n+ locked.set(true);\nreturn null;\n});\n- } catch (Exception ex) {\n- LOG.error(\"Thread terminated with an exception\", ex);\n- return null;\n+ sem.release();\n+ locked.set(false);\n+ return val;\n+ } finally {\n+ if (locked.get()) {\n+ sem.release();\n+ }\n}\n};\n- es.invokeAll(\n- IntStream.range(0, numThreads)\n+\n+ // submit tasks, and wait for the results without cancelling execution so that we'll be able to analyze the thread dump\n+ List<? extends Future<?>> tasks = IntStream.range(0, numThreads)\n.mapToObj(i -> independentTask)\n- .collect(Collectors.toList()),\n- timeoutSeconds, TimeUnit.SECONDS\n- );\n+ .map(es::submit).collect(Collectors.toList());\n+ long limit = System.currentTimeMillis() + timeoutSeconds * 1000L;\n+ for (Future<?> future : tasks) {\n+ long limitForTask = limit - System.currentTimeMillis();\n+ if (limitForTask > 0) {\n+ try {\n+ future.get(limitForTask, TimeUnit.MILLISECONDS);\n+ } catch (ExecutionException e) {\n+ if (e.getCause() instanceof AssertionError) {\n+ throw (AssertionError) e.getCause();\n+ } else {\n+ LOG.error(\"Execution didn't complete\", e);\n+ Assert.fail(\"Execution didn't complete: \" + e.getMessage());\n+ }\n+ } catch (TimeoutException e) {\n+ failWithThreadDump(threads, e);\n+ }\n+ } else {\n+ failWithThreadDump(threads, null);\n+ }\n+ }\n} finally {\n- LOG.debugf(\"waiting for threads to shutdown to avoid that one test pollutes another test\");\n- es.shutdown();\n- LOG.debugf(\"shutdown of threads complete\");\n+ es.shutdownNow();\n}\n+ // wait for shutdown executor pool, but not if there has been an exception\n+ if (!es.awaitTermination(10, TimeUnit.SECONDS)) {\n+ failWithThreadDump(threads, null);\n+ }\n+ }\n+\n+ private static void enabledContentionMonitoring() {\n+ if (!ManagementFactory.getThreadMXBean().isThreadContentionMonitoringEnabled()) {\n+ ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);\n+ }\n+ }\n+\n+ private static void failWithThreadDump(LinkedList<Thread> threads, Exception e) {\n+ ThreadInfo[] infos = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);\n+ List<String> liveStacks = Arrays.stream(infos).map(thread -> {\n+ StringBuilder sb = new StringBuilder();\n+ if (threads.stream().anyMatch(t -> t.getId() == thread.getThreadId())) {\n+ sb.append(\"[OurThreadPool] \");\n+ }\n+ sb.append(thread.getThreadName()).append(\" (\").append(thread.getThreadState()).append(\"):\");\n+ LockInfo lockInfo = thread.getLockInfo();\n+ if (lockInfo != null) {\n+ sb.append(\" locked on \").append(lockInfo);\n+ if (thread.getWaitedTime() != -1) {\n+ sb.append(\" waiting for \").append(thread.getWaitedTime()).append(\" ms\");\n+ }\n+ if (thread.getBlockedTime() != -1) {\n+ sb.append(\" blocked for \").append(thread.getBlockedTime()).append(\" ms\");\n+ }\n+ }\n+ sb.append(\"\\n\");\n+ for (StackTraceElement traceElement : thread.getStackTrace()) {\n+ sb.append(\"\\tat \").append(traceElement).append(\"\\n\");\n+ }\n+ return sb.toString();\n+ }).collect(Collectors.toList());\n+ throw new AssertionError(\"threads didn't terminate in time: \" + liveStacks, e);\n}\n/**\n@@ -376,10 +481,46 @@ public abstract class KeycloakModelTest {\nthrow new IllegalStateException(\"USE_DEFAULT_FACTORY must be false to use an independent factory\");\n}\nKeycloakSessionFactory original = getFactory();\n- KeycloakSessionFactory factory = createKeycloakSessionFactory();\n+ int retries = 10;\n+ KeycloakSessionFactory factory = null;\n+ do {\n+ try {\n+ factory = createKeycloakSessionFactory();\n+ } catch (CacheConfigurationException | EmbeddedCacheManagerStartupException ex) {\n+ if (retries > 0) {\n+ /*\n+ workaround for Infinispan 12.1.7.Final for a NullPointerException\n+ when multiple nodes tried to join at the same time. Retry until this succeeds.\n+ Already fixed in Infinispan 13.\n+ https://issues.redhat.com/browse/ISPN-13231\n+ */\n+ LOG.warn(\"initialization failed, retrying\", ex);\n+ --retries;\n+ } else {\n+ throw ex;\n+ }\n+ }\n+ } while (factory == null);\ntry {\nsetFactory(factory);\n+ do {\n+ try {\nreturn task.call();\n+ } catch (CacheConfigurationException | EmbeddedCacheManagerStartupException ex) {\n+ if (retries > 0) {\n+ /*\n+ workaround for Infinispan 12.1.7.Final for a NullPointerException\n+ when multiple nodes tried to join at the same time. Retry until this succeeds.\n+ Already fixed in Infinispan 13.\n+ https://issues.redhat.com/browse/ISPN-13231\n+ */\n+ LOG.warn(\"initialization failed, retrying\", ex);\n+ -- retries;\n+ } else {\n+ throw ex;\n+ }\n+ }\n+ } while (true);\n} catch (Exception ex) {\nthrow new RuntimeException(ex);\n} finally {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/UserModelTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/UserModelTest.java", "diff": "@@ -20,6 +20,7 @@ import org.keycloak.component.ComponentModel;\nimport org.keycloak.models.Constants;\nimport org.keycloak.models.GroupModel;\nimport org.keycloak.models.KeycloakSession;\n+import org.keycloak.models.ModelException;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.models.RealmProvider;\nimport org.keycloak.models.UserModel;\n@@ -39,6 +40,8 @@ import java.util.stream.IntStream;\nimport org.hamcrest.Matchers;\nimport org.junit.Test;\n+import javax.naming.NamingException;\n+\nimport static org.hamcrest.Matchers.hasItem;\nimport static org.hamcrest.Matchers.hasSize;\nimport static org.hamcrest.Matchers.is;\n@@ -213,7 +216,16 @@ public class UserModelTest extends KeycloakModelTest {\nlog.debugf(\"Removing selected users from backend\");\nIntStream.range(FIRST_DELETED_USER_INDEX, LAST_DELETED_USER_INDEX).forEach(j -> {\nfinal UserModel user = session.users().getUserByUsername(realm, \"user-\" + j);\n+ try {\n+ ((UserRegistrationProvider) instance).removeUser(realm, user);\n+ } catch (ModelException ex) {\n+ // removing user might have failed for an LDAP reason\n+ // as this is not the main subject under test, retry once more to delete the entry\n+ if (ex.getMessage().contains(\"Could not unbind DN\") && ex.getCause() instanceof NamingException) {\n+ log.warn(\"removing failed, retrying\", ex);\n((UserRegistrationProvider) instance).removeUser(realm, user);\n+ }\n+ }\n});\nreturn null;\n});\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/infinispan/CacheExpirationTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/infinispan/CacheExpirationTest.java", "diff": "@@ -37,7 +37,6 @@ import java.util.regex.Pattern;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.greaterThanOrEqualTo;\n-import static org.hamcrest.Matchers.is;\nimport static org.hamcrest.Matchers.notNullValue;\nimport static org.junit.Assume.assumeThat;\n@@ -54,6 +53,8 @@ public class CacheExpirationTest extends KeycloakModelTest {\n@Test\npublic void testCacheExpiration() throws Exception {\n+ log.debugf(\"Number of previous instances of the class on the heap: %d\", getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class));\n+\nlog.debug(\"Put two events to the main cache\");\ninComittedTransaction(session -> {\nInfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\n@@ -71,12 +72,17 @@ public class CacheExpirationTest extends KeycloakModelTest {\n// Ensure that instance counting works as expected, there should be at least two instances in memory now.\n// Infinispan server is decoding the client request before processing the request at the cache level,\n// therefore there are sometimes three instances of AuthenticationSessionAuthNoteUpdateEvent class in the memory\n- assertThat(getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class), greaterThanOrEqualTo(2));\n+ Integer instancesAfterInsertion = getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class);\n+ assertThat(instancesAfterInsertion, greaterThanOrEqualTo(2));\n+\n+ // A third instance created when inserting the instances is never collected from GC for a yet unknown reason.\n+ // Therefore, ignore this additional instance in the upcoming tests.\n+ int previousInstancesOfClass = instancesAfterInsertion - 2;\n+ log.debug(\"Expecting instance count to go down to \" + previousInstancesOfClass);\nlog.debug(\"Starting other nodes and see that they join, receive the data and have their data expired\");\n- AtomicInteger completedTests = new AtomicInteger(0);\n- inIndependentFactories(NUM_EXTRA_FACTORIES, 5 * 60, () -> {\n+ inIndependentFactories(NUM_EXTRA_FACTORIES, 2 * 60, () -> {\nlog.debug(\"Joining the cluster\");\ninComittedTransaction(session -> {\nInfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\n@@ -108,15 +114,12 @@ public class CacheExpirationTest extends KeycloakModelTest {\nlog.debug(\"Waiting for garbage collection to collect the entries across all caches in JVM\");\ndo {\ntry { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n- } while (getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class) != 0);\n+ } while (getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class) > previousInstancesOfClass);\n- completedTests.incrementAndGet();\nlog.debug(\"Test completed\");\n});\n});\n-\n- assertThat(completedTests.get(), is(NUM_EXTRA_FACTORIES));\n}\nprivate static final Pattern JMAP_HOTSPOT_PATTERN = Pattern.compile(\"\\\\s*\\\\d+:\\\\s+(\\\\d+)\\\\s+(\\\\d+)\\\\s+(\\\\S+)\\\\s*\");\n@@ -132,7 +135,9 @@ public class CacheExpirationTest extends KeycloakModelTest {\npublic synchronized Integer getNumberOfInstancesOfClass(Class<?> c, String pid) {\nProcess proc;\ntry {\n- // running this command will also trigger a garbage collection on the VM\n+ // running jmap command will also trigger a garbage collection on the VM, but that might be VM specific\n+ // a test run with adding \"-verbose:gc\" showed the message \"GC(23) Pause Full (Heap Inspection Initiated GC)\" that\n+ // indicates a full GC run\nproc = Runtime.getRuntime().exec(\"jmap -histo:live \" + pid);\ntry (BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/OfflineSessionPersistenceTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/OfflineSessionPersistenceTest.java", "diff": "@@ -33,11 +33,14 @@ import org.keycloak.services.managers.RealmManager;\nimport org.keycloak.testsuite.model.KeycloakModelTest;\nimport org.keycloak.testsuite.model.RequireProvider;\nimport java.util.Collection;\n+import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\n+import java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n+import java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Consumer;\nimport java.util.stream.Collectors;\n@@ -130,6 +133,8 @@ public class OfflineSessionPersistenceTest extends KeycloakModelTest {\n}\n@Test(timeout = 90 * 1000)\n+ @RequireProvider(UserSessionPersisterProvider.class)\n+ @RequireProvider(value = UserSessionProvider.class, only = InfinispanUserSessionProviderFactory.PROVIDER_ID)\npublic void testPersistenceMultipleNodesClientSessionAtSameNode() throws InterruptedException {\nList<String> clientIds = withRealm(realmId, (session, realm) -> {\nreturn IntStream.range(0, 5)\n@@ -140,30 +145,30 @@ public class OfflineSessionPersistenceTest extends KeycloakModelTest {\n// Shutdown factory -> enforce session persistence\ncloseKeycloakSessionFactory();\n-\n- Map<String, List<String>> clientSessionIds = new ConcurrentHashMap<>();\n- inIndependentFactories(3, 30, () -> {\n+ Set<String> clientSessionIds = Collections.newSetFromMap(new ConcurrentHashMap<>());\n+ inIndependentFactories(3, 60, () -> {\nwithRealm(realmId, (session, realm) -> {\n// Create offline sessions\nuserIds.forEach(userId -> createOfflineSessions(session, realm, userId, offlineUserSession -> {\n- List<String> innerClientSessionIds = IntStream.range(0, 5)\n+ IntStream.range(0, 5)\n.mapToObj(cid -> session.clients().getClientById(realm, clientIds.get(cid)))\n// TODO in the future: The following two lines are weird. Why an online client session needs to exist in order to create an offline one?\n.map(client -> session.sessions().createClientSession(realm, client, offlineUserSession))\n.map(clientSession -> session.sessions().createOfflineClientSession(clientSession, offlineUserSession))\n.map(AuthenticatedClientSessionModel::getId)\n- .collect(Collectors.toList());\n- clientSessionIds.put(offlineUserSession.getId(), innerClientSessionIds);\n- }));\n+ .forEach(s -> {}); // ensure that stream is consumed\n+ }).forEach(userSessionModel -> clientSessionIds.add(userSessionModel.getId())));\nreturn null;\n});\n});\nreinitializeKeycloakSessionFactory();\n- inIndependentFactories(4, 30, () -> assertOfflineSessionsExist(realmId, clientSessionIds.keySet()));\n+ inIndependentFactories(4, 30, () -> assertOfflineSessionsExist(realmId, clientSessionIds));\n}\n@Test(timeout = 90 * 1000)\n+ @RequireProvider(UserSessionPersisterProvider.class)\n+ @RequireProvider(value = UserSessionProvider.class, only = InfinispanUserSessionProviderFactory.PROVIDER_ID)\npublic void testPersistenceMultipleNodesClientSessionsAtRandomNode() throws InterruptedException {\nList<String> clientIds = withRealm(realmId, (session, realm) -> {\nreturn IntStream.range(0, 5)\n@@ -178,7 +183,7 @@ public class OfflineSessionPersistenceTest extends KeycloakModelTest {\nMap<String, List<String>> clientSessionIds = new ConcurrentHashMap<>();\nAtomicInteger i = new AtomicInteger();\n- inIndependentFactories(3, 30, () -> {\n+ inIndependentFactories(3, 60, () -> {\nfor (int j = 0; j < USER_COUNT * 3; j ++) {\nint index = i.incrementAndGet();\nint oid = index % offlineSessionIds.size();\n@@ -187,9 +192,13 @@ public class OfflineSessionPersistenceTest extends KeycloakModelTest {\nString clientSessionId = createOfflineClientSession(offlineSessionId, clientIds.get(cid));\nclientSessionIds.computeIfAbsent(offlineSessionId, a -> new LinkedList<>()).add(clientSessionId);\nif (index % 100 == 0) {\n+ // don't re-initialize all caches at the same time to avoid an unstable cluster with no leader\n+ // otherwise seen CacheInitializer#loadSessions to loop sleeping\n+ synchronized (OfflineSessionPersistenceTest.class) {\nreinitializeKeycloakSessionFactory();\n}\n}\n+ }\n});\nreinitializeKeycloakSessionFactory();\n@@ -282,6 +291,8 @@ public class OfflineSessionPersistenceTest extends KeycloakModelTest {\n}\n@Test(timeout = 90 * 1000)\n+ @RequireProvider(UserSessionPersisterProvider.class)\n+ @RequireProvider(value = UserSessionProvider.class, only = InfinispanUserSessionProviderFactory.PROVIDER_ID)\npublic void testPersistenceClientSessionsMultipleNodes() throws InterruptedException {\n// Create offline sessions\nList<String> offlineSessionIds = createOfflineSessions(realmId, userIds);\n@@ -294,19 +305,16 @@ public class OfflineSessionPersistenceTest extends KeycloakModelTest {\n/**\n* Assert that all the offline sessions passed in the {@code offlineSessionIds} parameter exist\n- * @param factory\n- * @param offlineSessionIds\n- * @return\n*/\n- private Void assertOfflineSessionsExist(String realmId, Collection<String> offlineSessionIds) {\n+ private void assertOfflineSessionsExist(String realmId, Collection<String> offlineSessionIds) {\nint foundOfflineSessions = withRealm(realmId, (session, realm) -> offlineSessionIds.stream()\n.map(offlineSessionId -> session.sessions().getOfflineUserSession(realm, offlineSessionId))\n.map(ous -> ous == null ? 0 : 1)\n.reduce(0, Integer::sum));\n- assertThat(foundOfflineSessions, Matchers.is(USER_COUNT * OFFLINE_SESSION_COUNT_PER_USER));\n-\n- return null;\n+ assertThat(foundOfflineSessions, Matchers.is(offlineSessionIds.size()));\n+ // catch a programming error where an empty collection of offline session IDs is passed\n+ assertThat(foundOfflineSessions, Matchers.greaterThan(0));\n}\n// ***************** Helper methods *****************\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionInitializerTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionInitializerTest.java", "diff": "@@ -38,6 +38,7 @@ import org.keycloak.models.sessions.infinispan.InfinispanUserSessionProviderFact\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Optional;\n+import java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.stream.Collectors;\n@@ -165,7 +166,7 @@ public class UserSessionInitializerTest extends KeycloakModelTest {\nOptional<HotRodServerRule> hotRodServer = getParameters(HotRodServerRule.class).findFirst();\n- inIndependentFactories(4, 300, () -> {\n+ inIndependentFactories(4, 60, () -> {\nsynchronized (lock) {\nif (index.incrementAndGet() == 1) {\n// create a user session in the first node\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionProviderOfflineModelTest.java", "new_path": "testsuite/model/src/test/java/org/keycloak/testsuite/model/session/UserSessionProviderOfflineModelTest.java", "diff": "@@ -314,33 +314,24 @@ public class UserSessionProviderOfflineModelTest extends KeycloakModelTest {\ncloseKeycloakSessionFactory();\n- AtomicBoolean result = new AtomicBoolean(true);\n- CountDownLatch latch = new CountDownLatch(4);\n- inIndependentFactories(4, 300, () -> {\n+ inIndependentFactories(4, 60, () -> {\nwithRealm(realmId, (session, realm) -> {\nfinal UserModel user = session.users().getUserByUsername(realm, \"user1\");\n- result.set(result.get() && assertOfflineSession(offlineUserSessions, session.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList())));\n+ Assert.assertTrue(assertOfflineSession(offlineUserSessions, session.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList())));\nreturn null;\n});\n-\n- latch.countDown();\n-\n- awaitLatch(latch);\n});\n- Assert.assertTrue(result.get());\n}\n@Test\npublic void testOfflineSessionLazyLoadingPropagationBetweenNodes() throws InterruptedException {\nAtomicReference<List<UserSessionModel>> offlineUserSessions = new AtomicReference<>(new LinkedList<>());\nAtomicReference<List<AuthenticatedClientSessionModel>> offlineClientSessions = new AtomicReference<>(new LinkedList<>());\n- AtomicBoolean result = new AtomicBoolean(true);\nAtomicInteger index = new AtomicInteger();\n- CountDownLatch latch = new CountDownLatch(4);\nCountDownLatch afterFirstNodeLatch = new CountDownLatch(1);\n- inIndependentFactories(4, 300, () -> {\n+ inIndependentFactories(4, 60, () -> {\nif (index.incrementAndGet() == 1) {\ncreateOfflineSessions(\"user1\", 10, offlineUserSessions, offlineClientSessions);\n@@ -352,25 +343,24 @@ public class UserSessionProviderOfflineModelTest extends KeycloakModelTest {\ninComittedTransaction(session -> {\nInfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);\nCache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);\n- do {\n+ while (! cache.getAdvancedCache().getDistributionManager().isJoinComplete()) {\ntry { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n- } while (! cache.getAdvancedCache().getDistributionManager().isJoinComplete());\n+ }\ncache.keySet().forEach(s -> {});\n});\nlog.debug(\"Cluster joined\");\nwithRealm(realmId, (session, realm) -> {\nfinal UserModel user = session.users().getUserByUsername(realm, \"user1\");\n- result.set(result.get() && assertOfflineSession(offlineUserSessions, session.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList())));\n+ // it might take a moment to propagate, therefore loop\n+ while (! assertOfflineSession(offlineUserSessions, session.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList()))) {\n+ try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); }\n+ }\nreturn null;\n});\n- latch.countDown();\n-\n- awaitLatch(latch);\n});\n- Assert.assertTrue(result.get());\n}\nprivate static Set<String> createOfflineSessionIncludeClientSessions(KeycloakSession session, UserSessionModel\n@@ -418,6 +408,8 @@ public class UserSessionProviderOfflineModelTest extends KeycloakModelTest {\ntry {\nlatch.await();\n} catch (InterruptedException e) {\n+ Thread.currentThread().interrupt();\n+ throw new RuntimeException(e);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/model/test-all-profiles.sh", "new_path": "testsuite/model/test-all-profiles.sh", "diff": "@@ -13,12 +13,15 @@ EXIT_CODE=0\nmvn clean\nfor I in `perl -ne 'print \"$1\\n\" if (m,<id>([^<]+)</id>,)' pom.xml`; do\necho \"========\"\n- echo \"======== Profile $I\"\n+ echo \"======== Start of Profile $I\"\necho \"========\"\n- mvn -B -Dsurefire.timeout=600 test \"-P$I\" \"$@\" 2>&1 | tee /tmp/surefire.out\n+ mvn -B -Dsurefire.timeout=900 test \"-P$I\" \"$@\" 2>&1 | tee /tmp/surefire.out\nEXIT_CODE=$[$EXIT_CODE + ${PIPESTATUS[0]}]\nmv target/surefire-reports \"target/surefire-reports-$I\"\nperl -ne \"print '::error::| $I | Timed out.' . \\\"\\n\\\" if (/There was a timeout in the fork/)\" /tmp/surefire.out\n+ echo \"========\"\n+ echo \"======== End of Profile $I\"\n+ echo \"========\"\ndone\n## If the jacoco file is present, generate reports in each of the model projects\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Ensure that Infinispan shutdowns correctly at the end of the tests. Report any exceptions within another thread as a test failure. Adding additional information like a thread dump when it doesn't shutdown as expected. Closes #10016
339,500
01.03.2022 08:37:55
-3,600
6c64d465eadb13471178548d78a35e87983860af
Convert authentication session entities into interface
[ { "change_type": "MODIFY", "old_path": "model/build-processor/src/main/java/org/keycloak/models/map/processor/Util.java", "new_path": "model/build-processor/src/main/java/org/keycloak/models/map/processor/Util.java", "diff": "@@ -102,7 +102,7 @@ public class Util {\npublic static String singularToPlural(String word) {\nif (word.endsWith(\"y\")) {\nreturn word.substring(0, word.length() -1) + \"ies\";\n- } else if (word.endsWith(\"ss\")) {\n+ } else if (word.endsWith(\"s\")) {\nreturn word + \"es\";\n} else {\nreturn word + \"s\";\n@@ -112,7 +112,7 @@ public class Util {\npublic static String pluralToSingular(String word) {\nif (word.endsWith(\"ies\")) {\nreturn word.substring(0, word.length() - 3) + \"y\";\n- } else if (word.endsWith(\"sses\")) {\n+ } else if (word.endsWith(\"ses\")) {\nreturn word.substring(0, word.length() - 2);\n} else {\nreturn word.endsWith(\"s\") ? word.substring(0, word.length() - 1) : word;\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionAdapter.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionAdapter.java", "diff": "@@ -23,11 +23,10 @@ import org.keycloak.models.UserModel;\nimport org.keycloak.sessions.AuthenticationSessionModel;\nimport org.keycloak.sessions.RootAuthenticationSessionModel;\n-import java.util.HashSet;\n+import java.util.Collections;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Set;\n-import java.util.concurrent.ConcurrentHashMap;\n/**\n* @author <a href=\"mailto:[email protected]\">Martin Kanis</a>\n@@ -59,20 +58,20 @@ public class MapAuthenticationSessionAdapter implements AuthenticationSessionMod\n@Override\npublic Map<String, ExecutionStatus> getExecutionStatus() {\n- return entity.getExecutionStatus();\n+ Map<String, ExecutionStatus> executionStatus = entity.getExecutionStatuses();\n+ return executionStatus == null ? Collections.emptyMap() : Collections.unmodifiableMap(executionStatus);\n}\n@Override\npublic void setExecutionStatus(String authenticator, ExecutionStatus status) {\nObjects.requireNonNull(authenticator, \"The provided authenticator can't be null!\");\nObjects.requireNonNull(status, \"The provided execution status can't be null!\");\n- parent.setUpdated(!Objects.equals(entity.getExecutionStatus().put(authenticator, status), status));\n+ this.entity.setExecutionStatus(authenticator, status);\n}\n@Override\npublic void clearExecutionStatus() {\n- parent.setUpdated(!entity.getExecutionStatus().isEmpty());\n- entity.getExecutionStatus().clear();\n+ entity.setExecutionStatuses(null);\n}\n@Override\n@@ -83,25 +82,25 @@ public class MapAuthenticationSessionAdapter implements AuthenticationSessionMod\n@Override\npublic void setAuthenticatedUser(UserModel user) {\nString userId = (user == null) ? null : user.getId();\n- parent.setUpdated(!Objects.equals(userId, entity.getAuthUserId()));\nentity.setAuthUserId(userId);\n}\n@Override\npublic Set<String> getRequiredActions() {\n- return new HashSet<>(entity.getRequiredActions());\n+ Set<String> requiredActions = entity.getRequiredActions();\n+ return requiredActions == null ? Collections.emptySet() : Collections.unmodifiableSet(requiredActions);\n}\n@Override\npublic void addRequiredAction(String action) {\nObjects.requireNonNull(action, \"The provided action can't be null!\");\n- parent.setUpdated(entity.getRequiredActions().add(action));\n+ entity.addRequiredAction(action);\n}\n@Override\npublic void removeRequiredAction(String action) {\nObjects.requireNonNull(action, \"The provided action can't be null!\");\n- parent.setUpdated(entity.getRequiredActions().remove(action));\n+ entity.removeRequiredAction(action);\n}\n@Override\n@@ -118,99 +117,77 @@ public class MapAuthenticationSessionAdapter implements AuthenticationSessionMod\n@Override\npublic void setUserSessionNote(String name, String value) {\n- if (name != null) {\n- if (value == null) {\n- parent.setUpdated(entity.getUserSessionNotes().remove(name) != null);\n- } else {\n- parent.setUpdated(!Objects.equals(entity.getUserSessionNotes().put(name, value), value));\n- }\n- }\n+ entity.setUserSessionNote(name, value);\n}\n@Override\npublic Map<String, String> getUserSessionNotes() {\n- return new ConcurrentHashMap<>(entity.getUserSessionNotes());\n+ Map<String, String> userSessionNotes = entity.getUserSessionNotes();\n+ return userSessionNotes == null ? Collections.emptyMap() : Collections.unmodifiableMap(userSessionNotes);\n}\n@Override\npublic void clearUserSessionNotes() {\n- parent.setUpdated(!entity.getUserSessionNotes().isEmpty());\n- entity.getUserSessionNotes().clear();\n+ entity.setUserSessionNotes(null);\n}\n@Override\npublic String getAuthNote(String name) {\n- return (name != null) ? entity.getAuthNotes().get(name) : null;\n+ Map<String, String> authNotes = entity.getAuthNotes();\n+ return (name != null && authNotes != null) ? authNotes.get(name) : null;\n}\n@Override\npublic void setAuthNote(String name, String value) {\n- if (name != null) {\n- if (value == null) {\n- parent.setUpdated(entity.getAuthNotes().remove(name) != null);\n- } else {\n- parent.setUpdated(!Objects.equals(entity.getAuthNotes().put(name, value), value));\n- }\n- }\n+ entity.setAuthNote(name, value);\n}\n@Override\npublic void removeAuthNote(String name) {\n- if (name != null) {\n- parent.setUpdated(entity.getAuthNotes().remove(name) != null);\n- }\n+ entity.removeAuthNote(name);\n}\n@Override\npublic void clearAuthNotes() {\n- parent.setUpdated(!entity.getAuthNotes().isEmpty());\n- entity.getAuthNotes().clear();\n+ entity.setAuthNotes(null);\n}\n@Override\npublic String getClientNote(String name) {\n- return (name != null) ? entity.getClientNotes().get(name) : null;\n+ return (name != null) ? getClientNotes().get(name) : null;\n}\n@Override\npublic void setClientNote(String name, String value) {\n- if (name != null) {\n- if (value == null) {\n- parent.setUpdated(entity.getClientNotes().remove(name) != null);\n- } else {\n- parent.setUpdated(!Objects.equals(entity.getClientNotes().put(name, value), value));\n- }\n- }\n+ entity.setClientNote(name, value);\n}\n@Override\npublic void removeClientNote(String name) {\n- if (name != null) {\n- parent.setUpdated(entity.getClientNotes().remove(name) != null);\n- }\n+ entity.removeClientNote(name);\n}\n@Override\npublic Map<String, String> getClientNotes() {\n- return new ConcurrentHashMap<>(entity.getClientNotes());\n+ Map<String, String> clientNotes = entity.getClientNotes();\n+ return clientNotes == null ? Collections.emptyMap() : Collections.unmodifiableMap(clientNotes);\n}\n@Override\npublic void clearClientNotes() {\n- parent.setUpdated(!entity.getClientNotes().isEmpty());\n- entity.getClientNotes().clear();\n+ entity.setClientNotes(null);\n}\n@Override\npublic Set<String> getClientScopes() {\n- return new HashSet<>(entity.getClientScopes());\n+ Set<String> clientScopes = entity.getClientScopes();\n+ return clientScopes == null ? Collections.emptySet() : Collections.unmodifiableSet(clientScopes);\n}\n@Override\npublic void setClientScopes(Set<String> clientScopes) {\nObjects.requireNonNull(clientScopes, \"The provided client scopes set can't be null!\");\n- parent.setUpdated(!Objects.equals(entity.getClientScopes(), clientScopes));\n- entity.setClientScopes(new HashSet<>(clientScopes));\n+ entity.setClientScopes(clientScopes);\n}\n@Override\n@@ -220,7 +197,6 @@ public class MapAuthenticationSessionAdapter implements AuthenticationSessionMod\n@Override\npublic void setRedirectUri(String uri) {\n- parent.setUpdated(!Objects.equals(entity.getRedirectUri(), uri));\nentity.setRedirectUri(uri);\n}\n@@ -241,7 +217,6 @@ public class MapAuthenticationSessionAdapter implements AuthenticationSessionMod\n@Override\npublic void setAction(String action) {\n- parent.setUpdated(!Objects.equals(entity.getAction(), action));\nentity.setAction(action);\n}\n@@ -252,7 +227,6 @@ public class MapAuthenticationSessionAdapter implements AuthenticationSessionMod\n@Override\npublic void setProtocol(String method) {\n- parent.setUpdated(!Objects.equals(entity.getProtocol(), method));\nentity.setProtocol(method);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionEntity.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionEntity.java", "diff": "*/\npackage org.keycloak.models.map.authSession;\n+import org.keycloak.models.map.annotations.GenerateEntityImplementations;\n+import org.keycloak.models.map.common.DeepCloner;\n+import org.keycloak.models.map.common.UpdatableEntity;\nimport org.keycloak.sessions.AuthenticationSessionModel;\n-import java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n-import java.util.concurrent.ConcurrentHashMap;\n/**\n* @author <a href=\"mailto:[email protected]\">Martin Kanis</a>\n*/\n-public class MapAuthenticationSessionEntity {\n+@GenerateEntityImplementations\[email protected]\n+public interface MapAuthenticationSessionEntity extends UpdatableEntity {\n- private String clientUUID;\n+ Map<String, String> getUserSessionNotes();\n+ void setUserSessionNotes(Map<String, String> userSessionNotes);\n+ void setUserSessionNote(String name, String value);\n- private String authUserId;\n+ String getClientUUID();\n+ void setClientUUID(String clientUUID);\n- private int timestamp;\n+ String getAuthUserId();\n+ void setAuthUserId(String authUserId);\n- private String redirectUri;\n- private String action;\n- private Set<String> clientScopes = new HashSet<>();\n+ Integer getTimestamp();\n+ void setTimestamp(Integer timestamp);\n- private Map<String, AuthenticationSessionModel.ExecutionStatus> executionStatus = new ConcurrentHashMap<>();\n- private String protocol;\n+ String getRedirectUri();\n+ void setRedirectUri(String redirectUri);\n- private Map<String, String> clientNotes= new ConcurrentHashMap<>();;\n- private Map<String, String> authNotes = new ConcurrentHashMap<>();;\n- private Set<String> requiredActions = new HashSet<>();\n- private Map<String, String> userSessionNotes = new ConcurrentHashMap<>();\n+ String getAction();\n+ void setAction(String action);\n- public Map<String, String> getUserSessionNotes() {\n- return userSessionNotes;\n- }\n-\n- public void setUserSessionNotes(Map<String, String> userSessionNotes) {\n- this.userSessionNotes = userSessionNotes;\n- }\n-\n- public String getClientUUID() {\n- return clientUUID;\n- }\n-\n- public void setClientUUID(String clientUUID) {\n- this.clientUUID = clientUUID;\n- }\n-\n- public String getAuthUserId() {\n- return authUserId;\n- }\n-\n- public void setAuthUserId(String authUserId) {\n- this.authUserId = authUserId;\n- }\n-\n- public int getTimestamp() {\n- return timestamp;\n- }\n-\n- public void setTimestamp(int timestamp) {\n- this.timestamp = timestamp;\n- }\n-\n- public String getRedirectUri() {\n- return redirectUri;\n- }\n-\n- public void setRedirectUri(String redirectUri) {\n- this.redirectUri = redirectUri;\n- }\n-\n- public String getAction() {\n- return action;\n- }\n+ Set<String> getClientScopes();\n+ void setClientScopes(Set<String> clientScopes);\n- public void setAction(String action) {\n- this.action = action;\n- }\n-\n- public Set<String> getClientScopes() {\n- return clientScopes;\n- }\n+ Set<String> getRequiredActions();\n+ void setRequiredActions(Set<String> requiredActions);\n+ void addRequiredAction(String requiredAction);\n+ void removeRequiredAction(String action);\n- public void setClientScopes(Set<String> clientScopes) {\n- this.clientScopes = clientScopes;\n- }\n+ String getProtocol();\n+ void setProtocol(String protocol);\n- public Set<String> getRequiredActions() {\n- return requiredActions;\n- }\n+ Map<String, String> getClientNotes();\n+ void setClientNotes(Map<String, String> clientNotes);\n+ void setClientNote(String name, String value);\n+ void removeClientNote(String name);\n- public void setRequiredActions(Set<String> requiredActions) {\n- this.requiredActions = requiredActions;\n- }\n+ Map<String, String> getAuthNotes();\n+ void setAuthNotes(Map<String, String> authNotes);\n+ void setAuthNote(String name, String value);\n+ void removeAuthNote(String name);\n- public String getProtocol() {\n- return protocol;\n- }\n-\n- public void setProtocol(String protocol) {\n- this.protocol = protocol;\n- }\n-\n- public Map<String, String> getClientNotes() {\n- return clientNotes;\n- }\n-\n- public void setClientNotes(Map<String, String> clientNotes) {\n- this.clientNotes = clientNotes;\n- }\n-\n- public Map<String, String> getAuthNotes() {\n- return authNotes;\n- }\n-\n- public void setAuthNotes(Map<String, String> authNotes) {\n- this.authNotes = authNotes;\n- }\n-\n- public Map<String, AuthenticationSessionModel.ExecutionStatus> getExecutionStatus() {\n- return executionStatus;\n- }\n-\n- public void setExecutionStatus(Map<String, AuthenticationSessionModel.ExecutionStatus> executionStatus) {\n- this.executionStatus = executionStatus;\n- }\n+ Map<String, AuthenticationSessionModel.ExecutionStatus> getExecutionStatuses();\n+ void setExecutionStatuses(Map<String, AuthenticationSessionModel.ExecutionStatus> executionStatus);\n+ void setExecutionStatus(String authenticator, AuthenticationSessionModel.ExecutionStatus status);\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapRootAuthenticationSessionAdapter.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapRootAuthenticationSessionAdapter.java", "diff": "@@ -24,8 +24,10 @@ import org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.sessions.AuthenticationSessionModel;\n+import java.util.Collections;\nimport java.util.Map;\nimport java.util.Objects;\n+import java.util.Optional;\nimport java.util.stream.Collectors;\n/**\n@@ -59,10 +61,9 @@ public class MapRootAuthenticationSessionAdapter extends AbstractRootAuthenticat\n@Override\npublic Map<String, AuthenticationSessionModel> getAuthenticationSessions() {\n- return entity.getAuthenticationSessions().entrySet()\n- .stream()\n+ return Optional.ofNullable(entity.getAuthenticationSessions()).orElseGet(Collections::emptyMap).entrySet().stream()\n.collect(Collectors.toMap(Map.Entry::getKey,\n- entry -> new MapAuthenticationSessionAdapter(session, this, entry.getKey(), entry.getValue())));\n+ entry -> new MapAuthenticationSessionAdapter(session, this, entry.getKey(), (MapAuthenticationSessionEntity) entry.getValue())));\n}\n@Override\n@@ -84,26 +85,27 @@ public class MapRootAuthenticationSessionAdapter extends AbstractRootAuthenticat\npublic AuthenticationSessionModel createAuthenticationSession(ClientModel client) {\nObjects.requireNonNull(client, \"The provided client can't be null!\");\n- MapAuthenticationSessionEntity authSessionEntity = new MapAuthenticationSessionEntity();\n+ MapAuthenticationSessionEntity authSessionEntity = new MapAuthenticationSessionEntityImpl();\nauthSessionEntity.setClientUUID(client.getId());\nint timestamp = Time.currentTime();\nauthSessionEntity.setTimestamp(timestamp);\nString tabId = generateTabId();\n- entity.getAuthenticationSessions().put(tabId, authSessionEntity);\n+ entity.setAuthenticationSession(tabId, authSessionEntity);\n// Update our timestamp when adding new authenticationSession\nentity.setTimestamp(timestamp);\n- MapAuthenticationSessionAdapter authSession = new MapAuthenticationSessionAdapter(session, this, tabId, authSessionEntity);\n+ MapAuthenticationSessionAdapter authSession = new MapAuthenticationSessionAdapter(session, this, tabId, entity.getAuthenticationSessions().get(tabId));\nsession.getContext().setAuthenticationSession(authSession);\nreturn authSession;\n}\n@Override\npublic void removeAuthenticationSessionByTabId(String tabId) {\n- if (entity.removeAuthenticationSession(tabId) != null) {\n+ Boolean result = entity.removeAuthenticationSession(tabId);\n+ if (result == null || result) {\nif (entity.getAuthenticationSessions().isEmpty()) {\nsession.authenticationSessions().removeRootAuthenticationSession(realm, this);\n} else {\n@@ -114,14 +116,10 @@ public class MapRootAuthenticationSessionAdapter extends AbstractRootAuthenticat\n@Override\npublic void restartSession(RealmModel realm) {\n- entity.clearAuthenticationSessions();\n+ entity.setAuthenticationSessions(null);\nentity.setTimestamp(Time.currentTime());\n}\n- public void setUpdated(boolean updated) {\n- entity.signalUpdated(updated);\n- }\n-\nprivate String generateTabId() {\nreturn Base64Url.encode(SecretGenerator.getInstance().randomBytes(8));\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapRootAuthenticationSessionEntity.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapRootAuthenticationSessionEntity.java", "diff": "*/\npackage org.keycloak.models.map.authSession;\n+import org.keycloak.models.map.annotations.GenerateEntityImplementations;\nimport org.keycloak.models.map.common.AbstractEntity;\n+import org.keycloak.models.map.common.DeepCloner;\nimport org.keycloak.models.map.common.UpdatableEntity;\n+\n+import java.util.Collections;\nimport java.util.Map;\n-import java.util.Objects;\n-import java.util.concurrent.ConcurrentHashMap;\n+import java.util.Optional;\n/**\n* @author <a href=\"mailto:[email protected]\">Martin Kanis</a>\n*/\n-public class MapRootAuthenticationSessionEntity extends UpdatableEntity.Impl implements AbstractEntity {\n-\n- private String id;\n- private String realmId;\n-\n- /**\n- * Flag signalizing that any of the setters has been meaningfully used.\n- */\n- private int timestamp;\n- private Map<String, MapAuthenticationSessionEntity> authenticationSessions = new ConcurrentHashMap<>();\n+@GenerateEntityImplementations(\n+ inherits = \"org.keycloak.models.map.authSession.MapRootAuthenticationSessionEntity.AbstractRootAuthenticationSessionEntity\"\n+)\[email protected]\n+public interface MapRootAuthenticationSessionEntity extends AbstractEntity, UpdatableEntity {\n- public MapRootAuthenticationSessionEntity() {}\n+ public abstract class AbstractRootAuthenticationSessionEntity extends UpdatableEntity.Impl implements MapRootAuthenticationSessionEntity {\n- public MapRootAuthenticationSessionEntity(String id, String realmId) {\n- this.id = id;\n- this.realmId = realmId;\n- }\n+ private String id;\n@Override\npublic String getId() {\n@@ -56,49 +51,27 @@ public class MapRootAuthenticationSessionEntity extends UpdatableEntity.Impl imp\nthis.updated |= id != null;\n}\n- public String getRealmId() {\n- return realmId;\n- }\n-\n- public void setRealmId(String realmId) {\n- this.updated |= !Objects.equals(this.realmId, realmId);\n- this.realmId = realmId;\n- }\n-\n- public int getTimestamp() {\n- return timestamp;\n- }\n-\n- public void setTimestamp(int timestamp) {\n- this.updated |= !Objects.equals(this.timestamp, timestamp);\n- this.timestamp = timestamp;\n- }\n-\n- public Map<String, MapAuthenticationSessionEntity> getAuthenticationSessions() {\n- return authenticationSessions;\n+ @Override\n+ public boolean isUpdated() {\n+ return this.updated ||\n+ Optional.ofNullable(getAuthenticationSessions()).orElseGet(Collections::emptyMap).values().stream().anyMatch(MapAuthenticationSessionEntity::isUpdated);\n}\n- public void setAuthenticationSessions(Map<String, MapAuthenticationSessionEntity> authenticationSessions) {\n- this.updated |= !Objects.equals(this.authenticationSessions, authenticationSessions);\n- this.authenticationSessions = authenticationSessions;\n+ @Override\n+ public void clearUpdatedFlag() {\n+ this.updated = false;\n+ Optional.ofNullable(getAuthenticationSessions()).orElseGet(Collections::emptyMap).values().forEach(UpdatableEntity::clearUpdatedFlag);\n}\n-\n- public MapAuthenticationSessionEntity removeAuthenticationSession(String tabId) {\n- MapAuthenticationSessionEntity entity = this.authenticationSessions.remove(tabId);\n- this.updated |= entity != null;\n- return entity;\n}\n- public void addAuthenticationSession(String tabId, MapAuthenticationSessionEntity entity) {\n- this.updated |= !Objects.equals(this.authenticationSessions.put(tabId, entity), entity);\n- }\n+ String getRealmId();\n+ void setRealmId(String realmId);\n- public void clearAuthenticationSessions() {\n- this.updated |= !this.authenticationSessions.isEmpty();\n- this.authenticationSessions.clear();\n- }\n+ Integer getTimestamp();\n+ void setTimestamp(Integer timestamp);\n- void signalUpdated(boolean updated) {\n- this.updated |= updated;\n- }\n+ Map<String, MapAuthenticationSessionEntity> getAuthenticationSessions();\n+ void setAuthenticationSessions(Map<String, MapAuthenticationSessionEntity> authenticationSessions);\n+ void setAuthenticationSession(String tabId, MapAuthenticationSessionEntity entity);\n+ Boolean removeAuthenticationSession(String tabId);\n}\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapRootAuthenticationSessionProvider.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/authSession/MapRootAuthenticationSessionProvider.java", "diff": "@@ -86,7 +86,9 @@ public class MapRootAuthenticationSessionProvider implements AuthenticationSessi\nLOG.tracef(\"createRootAuthenticationSession(%s)%s\", realm.getName(), getShortStackTrace());\n// create map authentication session entity\n- MapRootAuthenticationSessionEntity entity = new MapRootAuthenticationSessionEntity(id, realm.getId());\n+ MapRootAuthenticationSessionEntity entity = new MapRootAuthenticationSessionEntityImpl();\n+ entity.setId(id);\n+ entity.setRealmId(realm.getId());\nentity.setTimestamp(Time.currentTime());\nif (id != null && tx.read(id) != null) {\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/storage/chm/ConcurrentHashMapStorageProviderFactory.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/storage/chm/ConcurrentHashMapStorageProviderFactory.java", "diff": "*/\npackage org.keycloak.models.map.storage.chm;\n+import org.keycloak.models.map.authSession.MapAuthenticationSessionEntity;\n+import org.keycloak.models.map.authSession.MapAuthenticationSessionEntityImpl;\n+import org.keycloak.models.map.authSession.MapRootAuthenticationSessionEntity;\n+import org.keycloak.models.map.authSession.MapRootAuthenticationSessionEntityImpl;\nimport org.keycloak.models.map.authorization.entity.MapPermissionTicketEntity;\nimport org.keycloak.models.map.authorization.entity.MapPermissionTicketEntityImpl;\nimport org.keycloak.models.map.authorization.entity.MapPolicyEntity;\n@@ -122,6 +126,8 @@ public class ConcurrentHashMapStorageProviderFactory implements AmphibianProvide\n.constructor(MapRequiredActionProviderEntity.class, MapRequiredActionProviderEntityImpl::new)\n.constructor(MapRequiredCredentialEntity.class, MapRequiredCredentialEntityImpl::new)\n.constructor(MapWebAuthnPolicyEntity.class, MapWebAuthnPolicyEntityImpl::new)\n+ .constructor(MapRootAuthenticationSessionEntity.class, MapRootAuthenticationSessionEntityImpl::new)\n+ .constructor(MapAuthenticationSessionEntity.class, MapAuthenticationSessionEntityImpl::new)\n.build();\nprivate static final Map<String, StringKeyConvertor> KEY_CONVERTORS = new HashMap<>();\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Convert authentication session entities into interface
339,511
04.03.2022 10:11:57
-32,400
201277b8973d1f6c866e0d6a6604ce2b257894f3
Handle OIDC authz request with "response_type" missing and "response_mode=form_post" Closes
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java", "diff": "@@ -151,7 +151,12 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {\nthis.parsedResponseType = checker.getParsedResponseType();\nthis.parsedResponseMode = checker.getParsedResponseMode();\n} catch (AuthorizationEndpointChecker.AuthorizationCheckException ex) {\n- OIDCResponseMode responseMode = checker.getParsedResponseMode() != null ? checker.getParsedResponseMode() : OIDCResponseMode.QUERY;\n+ OIDCResponseMode responseMode = null;\n+ if (checker.isInvalidResponseType(ex)) {\n+ responseMode = OIDCResponseMode.parseWhenInvalidResponseType(request.getResponseMode());\n+ } else {\n+ responseMode = checker.getParsedResponseMode() != null ? checker.getParsedResponseMode() : OIDCResponseMode.QUERY;\n+ }\nreturn redirectErrorToClient(responseMode, ex.getError(), ex.getErrorDescription());\n}\nif (action == null) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpointChecker.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpointChecker.java", "diff": "@@ -193,6 +193,10 @@ public class AuthorizationEndpointChecker {\n}\n}\n+ public boolean isInvalidResponseType(AuthorizationEndpointChecker.AuthorizationCheckException ex) {\n+ return \"Missing parameter: response_type\".equals(ex.getErrorDescription()) || OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE.equals(ex.getError());\n+ }\n+\npublic void checkInvalidRequestMessage() throws AuthorizationCheckException {\nif (request.getInvalidRequestMessage() != null) {\nevent.error(Errors.INVALID_REQUEST);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/OIDCResponseMode.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/utils/OIDCResponseMode.java", "diff": "@@ -46,6 +46,21 @@ public enum OIDCResponseMode {\n}\n}\n+ public static OIDCResponseMode parseWhenInvalidResponseType(String responseMode) {\n+ if (responseMode == null) {\n+ return OIDCResponseMode.QUERY;\n+ } else if(responseMode.equals(\"jwt\")) {\n+ return OIDCResponseMode.QUERY_JWT;\n+ } else {\n+ for (OIDCResponseMode c : OIDCResponseMode.values()) {\n+ if (c.value.equals(responseMode)) {\n+ return c;\n+ }\n+ }\n+ return OIDCResponseMode.QUERY;\n+ }\n+ }\n+\npublic String value() {\nreturn value;\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AuthorizationCodeTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AuthorizationCodeTest.java", "diff": "@@ -158,6 +158,40 @@ public class AuthorizationCodeTest extends AbstractKeycloakTest {\nevents.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().detail(Details.RESPONSE_TYPE, \"tokenn\").assertEvent();\n}\n+ @Test\n+ public void authorizationRequestFormPostResponseModeInvalidResponseType() throws IOException {\n+ oauth.responseMode(OIDCResponseMode.FORM_POST.value());\n+ oauth.responseType(\"tokenn\");\n+ oauth.stateParamHardcoded(\"OpenIdConnect.AuthenticationProperties=2302984sdlk\");\n+ UriBuilder b = UriBuilder.fromUri(oauth.getLoginFormUrl());\n+ driver.navigate().to(b.build().toURL());\n+\n+ String error = driver.findElement(By.id(\"error\")).getText();\n+ String state = driver.findElement(By.id(\"state\")).getText();\n+\n+ assertEquals(OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE, error);\n+ assertEquals(\"OpenIdConnect.AuthenticationProperties=2302984sdlk\", state);\n+\n+ }\n+\n+ @Test\n+ public void authorizationRequestFormPostResponseModeWithoutResponseType() throws IOException {\n+ oauth.responseMode(OIDCResponseMode.FORM_POST.value());\n+ oauth.responseType(null);\n+ oauth.stateParamHardcoded(\"OpenIdConnect.AuthenticationProperties=2302984sdlk\");\n+ UriBuilder b = UriBuilder.fromUri(oauth.getLoginFormUrl());\n+ driver.navigate().to(b.build().toURL());\n+\n+ String error = driver.findElement(By.id(\"error\")).getText();\n+ String errorDescription = driver.findElement(By.id(\"error_description\")).getText();\n+ String state = driver.findElement(By.id(\"state\")).getText();\n+\n+ assertEquals(OAuthErrorException.INVALID_REQUEST, error);\n+ assertEquals(\"Missing parameter: response_type\", errorDescription);\n+ assertEquals(\"OpenIdConnect.AuthenticationProperties=2302984sdlk\", state);\n+\n+ }\n+\n// KEYCLOAK-3281\n@Test\npublic void authorizationRequestFormPostResponseMode() throws IOException {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Handle OIDC authz request with "response_type" missing and "response_mode=form_post" Closes #10144
339,604
17.02.2022 10:55:04
28,800
722ce950bfa477008016b148a07d20568a364b6b
Improve user search performance Removes bulder.lower() from user search queries on email and username. Closes
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java", "diff": "@@ -812,16 +812,22 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor\npredicates.add(builder.or(getSearchOptionPredicateArray(stringToSearch, builder, root)));\n}\nbreak;\n- case USERNAME:\ncase FIRST_NAME:\ncase LAST_NAME:\n- case EMAIL:\nif (Boolean.valueOf(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString()))) {\npredicates.add(builder.equal(builder.lower(root.get(key)), value.toLowerCase()));\n} else {\npredicates.add(builder.like(builder.lower(root.get(key)), \"%\" + value.toLowerCase() + \"%\"));\n}\nbreak;\n+ case USERNAME:\n+ case EMAIL:\n+ if (Boolean.valueOf(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString()))) {\n+ predicates.add(builder.equal(root.get(key), value.toLowerCase()));\n+ } else {\n+ predicates.add(builder.like(root.get(key), \"%\" + value.toLowerCase() + \"%\"));\n+ }\n+ break;\ncase EMAIL_VERIFIED:\npredicates.add(builder.equal(root.get(key), Boolean.parseBoolean(value.toLowerCase())));\nbreak;\n@@ -1050,8 +1056,8 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor\n// exact search\nvalue = value.substring(1, value.length() - 1);\n- orPredicates.add(builder.equal(builder.lower(from.get(USERNAME)), value));\n- orPredicates.add(builder.equal(builder.lower(from.get(EMAIL)), value));\n+ orPredicates.add(builder.equal(from.get(USERNAME), value));\n+ orPredicates.add(builder.equal(from.get(EMAIL), value));\norPredicates.add(builder.equal(builder.lower(from.get(FIRST_NAME)), value));\norPredicates.add(builder.equal(builder.lower(from.get(LAST_NAME)), value));\n} else {\n@@ -1066,8 +1072,8 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor\nvalue += \"%\";\n}\n- orPredicates.add(builder.like(builder.lower(from.get(USERNAME)), value));\n- orPredicates.add(builder.like(builder.lower(from.get(EMAIL)), value));\n+ orPredicates.add(builder.like(from.get(USERNAME), value));\n+ orPredicates.add(builder.like(from.get(EMAIL), value));\norPredicates.add(builder.like(builder.lower(from.get(FIRST_NAME)), value));\norPredicates.add(builder.like(builder.lower(from.get(LAST_NAME)), value));\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountFormServiceTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountFormServiceTest.java", "diff": "@@ -862,6 +862,80 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {\nsetEditUsernameAllowed(false);\n}\n+ // KEYCLOAK-8893\n+ @Test\n+ public void caseInsensitiveSearchWorksWithoutForcingLowercaseOnEmailAttribute() throws Exception {\n+ setEditUsernameAllowed(true);\n+ setRegistrationEmailAsUsername(true);\n+\n+ profilePage.open();\n+ loginPage.login(\"test-user@localhost\", \"password\");\n+ assertFalse(driver.findElements(By.id(\"username\")).size() > 0);\n+\n+ profilePage.updateProfile(\"New First\", \"New Last\", \"New-Email@email\");\n+\n+ Assert.assertEquals(\"Your account has been updated.\", profilePage.getSuccess());\n+ Assert.assertEquals(\"New First\", profilePage.getFirstName());\n+ Assert.assertEquals(\"New Last\", profilePage.getLastName());\n+ Assert.assertEquals(\"new-email@email\", profilePage.getEmail()); // verify attribute is lower case after save\n+\n+ List<UserRepresentation> list = adminClient.realm(\"test\").users().search(null, null, null, \"nEw-emAil@eMail\", null, null);\n+ assertEquals(1, list.size());\n+\n+ UserRepresentation user = list.get(0);\n+\n+ assertEquals(\"new-email@email\", user.getUsername());\n+\n+ list = adminClient.realm(\"test\").users().search(\"nEw-emAil@eMail\", null, null, null, null, null);\n+ assertEquals(1, list.size());\n+\n+ user = list.get(0);\n+\n+ assertEquals(\"new-email@email\", user.getUsername());\n+\n+ list = adminClient.realm(\"test\").users().search(null, \"new fIrSt\", null, null, null, null);\n+ assertEquals(1, list.size());\n+\n+ user = list.get(0);\n+\n+ assertEquals(\"new-email@email\", user.getUsername());\n+\n+ list = adminClient.realm(\"test\").users().search(null, null, \"NEw LaST\", null, null, null);\n+ assertEquals(1, list.size());\n+\n+ user = list.get(0);\n+\n+ assertEquals(\"new-email@email\", user.getUsername());\n+\n+ assertEquals(\"New First\", user.getFirstName());\n+ assertEquals(\"New Last\", user.getLastName());\n+\n+ list = adminClient.realm(\"test\").users().search(\"nEw-emAil@eMail\", 0, 1);\n+ assertEquals(1, list.size());\n+\n+ user = list.get(0);\n+\n+ assertEquals(\"new-email@email\", user.getUsername());\n+\n+ list = adminClient.realm(\"test\").users().search(\"nEw\", 0, 1);\n+ assertEquals(1, list.size());\n+\n+ user = list.get(0);\n+\n+ assertEquals(\"new-email@email\", user.getUsername());\n+\n+ // Revert\n+\n+ user.setUsername(\"test-user@localhost\");\n+ user.setFirstName(\"Tom\");\n+ user.setLastName(\"Brady\");\n+ user.setEmail(\"test-user@localhost\");\n+ adminClient.realm(\"test\").users().get(user.getId()).update(user);\n+\n+ setRegistrationEmailAsUsername(false);\n+ setEditUsernameAllowed(false);\n+ }\n+\nprivate void setEditUsernameAllowed(boolean allowed) {\nRealmRepresentation testRealm = testRealm().toRepresentation();\ntestRealm.setEditUsernameAllowed(allowed);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Improve user search performance Removes bulder.lower() from user search queries on email and username. Closes #8893
339,410
02.03.2022 12:50:09
-3,600
e1318d52d7ce8052a198c425ca773d1d5ba7aef8
Add section on how to add the initial admin user Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/configuration.adoc", "new_path": "docs/guides/src/main/server/configuration.adoc", "diff": "@@ -154,6 +154,14 @@ is needed for deploying Keycloak in production.\nBy default, the configuration options for the production mode are commented out in the `conf/keycloak.conf`. These examples\nare meant to give you an idea about the main settings to consider when running in production.\n+== Setup of the initial admin user\n+\n+The initial admin user can be added manually using the web frontend when accessed from localhost or automatically using environment variables.\n+\n+To add the initial admin user using environment variables, set `KEYCLOAK_ADMIN` for the initial admin username and `KEYCLOAK_ADMIN_PASSWORD` for the initial admin password.\n+Keycloak uses them at the first startup to create an initial user with administration rights.\n+Once the first user with administrative rights exists, you can use the UI or the command line tool `kcadm.[sh|bat]` to create additional users.\n+\n== Unsupported server options\nIn most cases, the available options from the server configuration should suffice to configure the server.\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add section on how to add the initial admin user Closes #10531 Co-authored-by: Dominik Guhr <[email protected]>
339,198
23.02.2022 19:48:35
-3,600
f569db2e427f2c2eda7b1aed549156e0ec878c08
Update kubernetes cache-stack documentation Closes
[ { "change_type": "MODIFY", "old_path": "docs/guides/src/main/server/caching.adoc", "new_path": "docs/guides/src/main/server/caching.adoc", "diff": "@@ -117,7 +117,12 @@ The following table shows transport stacks that are available without any furthe\n|Stack name|Transport protocol|Discovery\n|tcp|TCP|MPING (uses UDP multicast).\n|udp|UDP|UDP multicast\n-|kubernetes|TCP|DNS_PING\n+|===\n+\n+The following table shows transport stacks that are available using the `--cache-stack` build option and a minimum configuration:\n+|===\n+|Stack name|Transport protocol|Discovery\n+|kubernetes|TCP|DNS_PING (requires `-Djgroups.dns.query=<headless-service-FQDN>` to be added to JAVA_OPTS or JAVA_OPTS_APPEND environment variable).\n|===\n=== Additional transport stacks\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Update kubernetes cache-stack documentation Closes #10341
339,179
01.03.2022 09:33:04
-3,600
f77ce315bbbd6b7c9ffe185faf9c1d15ebae95c4
Disable Authz caching for new storage tests Closes
[ { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/authorization/MapPermissionTicketStore.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/authorization/MapPermissionTicketStore.java", "diff": "@@ -19,6 +19,7 @@ package org.keycloak.models.map.authorization;\nimport org.jboss.logging.Logger;\nimport org.keycloak.authorization.AuthorizationProvider;\n+import org.keycloak.authorization.UserManagedPermissionUtil;\nimport org.keycloak.authorization.model.PermissionTicket;\nimport org.keycloak.authorization.model.PermissionTicket.SearchableFields;\nimport org.keycloak.authorization.model.Resource;\n@@ -129,7 +130,12 @@ public class MapPermissionTicketStore implements PermissionTicketStore {\n@Override\npublic void delete(String id) {\nLOG.tracef(\"delete(%s)%s\", id, getShortStackTrace());\n+\n+ PermissionTicket permissionTicket = findById(id, null);\n+ if (permissionTicket == null) return;\n+\ntx.delete(id);\n+ UserManagedPermissionUtil.removePolicy(permissionTicket, authorizationProvider.getStoreFactory());\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "model/map/src/main/java/org/keycloak/models/map/authorization/adapter/MapResourceAdapter.java", "new_path": "model/map/src/main/java/org/keycloak/models/map/authorization/adapter/MapResourceAdapter.java", "diff": "package org.keycloak.models.map.authorization.adapter;\n+import org.keycloak.authorization.model.PermissionTicket;\nimport org.keycloak.authorization.model.Scope;\n+import org.keycloak.authorization.store.PermissionTicketStore;\n+import org.keycloak.authorization.store.PolicyStore;\nimport org.keycloak.authorization.store.StoreFactory;\nimport org.keycloak.models.map.authorization.entity.MapResourceEntity;\n@@ -129,6 +132,25 @@ public class MapResourceAdapter extends AbstractResourceModel<MapResourceEntity>\n@Override\npublic void updateScopes(Set<Scope> scopes) {\nthrowExceptionIfReadonly();\n+\n+ PermissionTicketStore permissionStore = storeFactory.getPermissionTicketStore();\n+ PolicyStore policyStore = storeFactory.getPolicyStore();\n+\n+ for (Scope scope : getScopes()) {\n+ if (!scopes.contains(scope)) {\n+ // The scope^ was removed from the Resource\n+\n+ // Remove permission tickets based on the scope\n+ List<PermissionTicket> permissions = permissionStore.findByScope(scope.getId(), getResourceServer());\n+ for (PermissionTicket permission : permissions) {\n+ permissionStore.delete(permission.getId());\n+ }\n+\n+ // Remove the scope from each Policy for this Resource\n+ policyStore.findByResource(getId(), getResourceServer(), policy -> policy.removeScope(scope));\n+ }\n+ }\n+\nentity.setScopeIds(scopes.stream().map(Scope::getId).collect(Collectors.toSet()));\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java", "new_path": "services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java", "diff": "@@ -494,13 +494,12 @@ public class AuthorizationTokenService {\n}\n}\n- resolvePreviousGrantedPermissions(ticket, request, resourceServer, permissionsToEvaluate, resourceStore, scopeStore, limit);\n+ resolvePreviousGrantedPermissions(request, resourceServer, permissionsToEvaluate, resourceStore, scopeStore, limit);\nreturn permissionsToEvaluate.values();\n}\n- private void resolvePreviousGrantedPermissions(PermissionTicketToken ticket,\n- KeycloakAuthorizationRequest request, ResourceServer resourceServer,\n+ private void resolvePreviousGrantedPermissions(KeycloakAuthorizationRequest request, ResourceServer resourceServer,\nMap<String, ResourcePermission> permissionsToEvaluate, ResourceStore resourceStore, ScopeStore scopeStore,\nAtomicInteger limit) {\nAccessToken rpt = request.getRpt();\n@@ -517,7 +516,7 @@ public class AuthorizationTokenService {\nbreak;\n}\n- Resource resource = resourceStore.findById(grantedPermission.getResourceId(), ticket.getIssuedFor());\n+ Resource resource = resourceStore.findById(grantedPermission.getResourceId(), resourceServer.getId());\nif (resource != null) {\nResourcePermission permission = permissionsToEvaluate.get(resource.getId());\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/pom.xml", "new_path": "testsuite/integration-arquillian/tests/base/pom.xml", "diff": "<keycloak.userSession.provider>map</keycloak.userSession.provider>\n<keycloak.loginFailure.provider>map</keycloak.loginFailure.provider>\n<keycloak.authorization.provider>map</keycloak.authorization.provider>\n+ <keycloak.authorizationCache.enabled>false</keycloak.authorizationCache.enabled>\n</systemPropertyVariables>\n</configuration>\n</plugin>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json", "new_path": "testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json", "diff": "}\n},\n+ \"authorizationCache\": {\n+ \"default\": {\n+ \"enabled\": \"${keycloak.authorizationCache.enabled:true}\"\n+ }\n+ },\n+\n\"userCache\": {\n\"provider\": \"${keycloak.user.cache.provider:default}\",\n\"default\" : {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Disable Authz caching for new storage tests Closes #10500
339,465
02.03.2022 16:08:20
-3,600
d394e51674ee8b4ec6531a9e19dd814923525d4a
Introduce profile 'feature' for step-up authentication enabled by default Closes
[ { "change_type": "MODIFY", "old_path": "common/src/main/java/org/keycloak/common/Profile.java", "new_path": "common/src/main/java/org/keycloak/common/Profile.java", "diff": "@@ -65,7 +65,8 @@ public class Profile {\nMAP_STORAGE(\"New store\", Type.EXPERIMENTAL),\nPAR(\"OAuth 2.0 Pushed Authorization Requests (PAR)\", Type.DEFAULT),\nDECLARATIVE_USER_PROFILE(\"Configure user profiles using a declarative style\", Type.PREVIEW),\n- DYNAMIC_SCOPES(\"Dynamic OAuth 2.0 scopes\", Type.EXPERIMENTAL);\n+ DYNAMIC_SCOPES(\"Dynamic OAuth 2.0 scopes\", Type.EXPERIMENTAL),\n+ STEP_UP_AUTHENTICATION(\"Step-up Authentication\", Type.DEFAULT);\nprivate String label;\nprivate final Type typeProject;\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/conditional/ConditionalLoaAuthenticatorFactory.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/conditional/ConditionalLoaAuthenticatorFactory.java", "diff": "@@ -21,13 +21,15 @@ import java.util.List;\nimport org.keycloak.Config;\nimport org.keycloak.authentication.AuthenticationFlowCallbackFactory;\nimport org.keycloak.authentication.Authenticator;\n+import org.keycloak.common.Profile;\nimport org.keycloak.models.AuthenticationExecutionModel;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.KeycloakSessionFactory;\n+import org.keycloak.provider.EnvironmentDependentProviderFactory;\nimport org.keycloak.provider.ProviderConfigProperty;\nimport org.keycloak.provider.ProviderConfigurationBuilder;\n-public class ConditionalLoaAuthenticatorFactory implements ConditionalAuthenticatorFactory, AuthenticationFlowCallbackFactory {\n+public class ConditionalLoaAuthenticatorFactory implements ConditionalAuthenticatorFactory, AuthenticationFlowCallbackFactory, EnvironmentDependentProviderFactory {\npublic static final String PROVIDER_ID = \"conditional-level-of-authentication\";\nprivate static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = new AuthenticationExecutionModel.Requirement[]{\n@@ -105,4 +107,9 @@ public class ConditionalLoaAuthenticatorFactory implements ConditionalAuthentica\n// NOP - instance created in create() method\nreturn null;\n}\n+\n+ @Override\n+ public boolean isSupported() {\n+ return Profile.isFeatureEnabled(Profile.Feature.STEP_UP_AUTHENTICATION);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "new_path": "services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java", "diff": "@@ -884,7 +884,13 @@ public class TokenManager {\ntoken.setNonce(clientSessionCtx.getAttribute(OIDCLoginProtocol.NONCE_PARAM, String.class));\ntoken.setScope(clientSessionCtx.getScopeString());\n+ if (Profile.isFeatureEnabled(Profile.Feature.STEP_UP_AUTHENTICATION)) {\ntoken.setAcr(getAcr(clientSession));\n+ } else {\n+ // Backwards compatibility behaviour prior step-up authentication was introduced\n+ String acr = AuthenticationManager.isSSOAuthentication(clientSession) ? \"0\" : \"1\";\n+ token.setAcr(acr);\n+ }\nString authTime = session.getNote(AuthenticationManager.AUTH_TIME);\nif (authTime != null) {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java", "diff": "@@ -31,11 +31,13 @@ import org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.keycloak.OAuth2Constants;\nimport org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.authentication.authenticators.browser.OTPFormAuthenticatorFactory;\nimport org.keycloak.authentication.authenticators.browser.UsernamePasswordFormFactory;\nimport org.keycloak.authentication.authenticators.conditional.ConditionalLoaAuthenticator;\nimport org.keycloak.authentication.authenticators.conditional.ConditionalLoaAuthenticatorFactory;\n+import org.keycloak.common.Profile;\nimport org.keycloak.events.Details;\nimport org.keycloak.models.AuthenticationExecutionModel.Requirement;\nimport org.keycloak.models.Constants;\n@@ -44,6 +46,7 @@ import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.representations.ClaimsRepresentation;\nimport org.keycloak.representations.IDToken;\n+import org.keycloak.representations.idm.AuthenticationFlowRepresentation;\nimport org.keycloak.representations.idm.ClientRepresentation;\nimport org.keycloak.representations.idm.EventRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\n@@ -51,9 +54,12 @@ import org.keycloak.representations.idm.UserRepresentation;\nimport org.keycloak.testsuite.AbstractTestRealmKeycloakTest;\nimport org.keycloak.testsuite.AssertEvents;\nimport org.keycloak.testsuite.admin.ApiUtil;\n+import org.keycloak.testsuite.admin.authentication.AbstractAuthenticationTest;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.arquillian.annotation.DisableFeature;\nimport org.keycloak.testsuite.authentication.PushButtonAuthenticatorFactory;\nimport org.keycloak.testsuite.client.KeycloakTestingClient;\n+import org.keycloak.testsuite.pages.AppPage;\nimport org.keycloak.testsuite.pages.ErrorPage;\nimport org.keycloak.testsuite.pages.LoginPage;\nimport org.keycloak.testsuite.pages.LoginTotpPage;\n@@ -66,6 +72,7 @@ import org.keycloak.testsuite.util.WaitUtils;\nimport org.keycloak.util.JsonSerialization;\nimport static org.hamcrest.CoreMatchers.is;\n+import static org.junit.Assert.assertEquals;\nimport static org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer.REMOTE;\n/**\n@@ -617,6 +624,26 @@ public class LevelOfAssuranceFlowTest extends AbstractTestRealmKeycloakTest {\n}\n+ @Test\n+ @DisableFeature(value = Profile.Feature.STEP_UP_AUTHENTICATION, skipRestart = true)\n+ public void testDisableStepupFeatureTest() {\n+ BrowserFlowTest.revertFlows(testRealm(), \"browser - Level of Authentication FLow\");\n+\n+ // Login normal way - should return 1 (backwards compatibility before step-up was introduced)\n+ loginPage.open();\n+ authenticateWithUsernamePassword();\n+ authenticateWithTotp(); // OTP required due the user has it\n+ assertLoggedInWithAcr(\"1\");\n+\n+ // SSO login - should return 0 (backwards compatibility before step-up was introduced)\n+ oauth.openLoginForm();\n+ assertLoggedInWithAcr(\"0\");\n+\n+ // Flow is needed due the \"after()\" method\n+ testingClient.server(TEST_REALM_NAME).run(session -> FlowUtil.inCurrentRealm(session).copyBrowserFlow(\"browser - Level of Authentication FLow\"));\n+ }\n+\n+\npublic void openLoginFormWithAcrClaim(boolean essential, String... acrValues) {\nopenLoginFormWithAcrClaim(oauth, essential, acrValues);\n}\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/client-detail.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/client-detail.html", "diff": "<kc-tooltip>{{:: 'require-pushed-authorization-requests.tooltip' | translate}}</kc-tooltip>\n</div>\n- <div class=\"form-group clearfix block\" data-ng-show=\"!clientEdit.bearerOnly && protocol == 'openid-connect'\">\n+ <div class=\"form-group clearfix block\" data-ng-show=\"!clientEdit.bearerOnly && protocol == 'openid-connect' && serverInfo.featureEnabled('STEP_UP_AUTHENTICATION')\">\n<label class=\"col-md-2 control-label\" for=\"newAcr\">{{:: 'acr-loa-map' | translate}}</label>\n<div class=\"col-sm-6\">\n<div class=\"input-group input-map\" ng-repeat=\"(acr, loa) in acrLoaMap\">\n<kc-tooltip>{{:: 'acr-loa-map-client.tooltip' | translate}}</kc-tooltip>\n</div>\n- <div class=\"form-group\" data-ng-show=\"!clientEdit.bearerOnly && protocol == 'openid-connect'\">\n+ <div class=\"form-group\" data-ng-show=\"!clientEdit.bearerOnly && protocol == 'openid-connect' && serverInfo.featureEnabled('STEP_UP_AUTHENTICATION')\">\n<label class=\"col-md-2 control-label\" for=\"newDefaultAcrValue\">{{:: 'default-acr-values' | translate}}</label>\n<div class=\"col-sm-6\">\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/realm-login-settings.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/realm-login-settings.html", "diff": "</div>\n<kc-tooltip>{{:: 'sslRequired.tooltip' | translate}}</kc-tooltip>\n</div>\n- <div class=\"form-group clearfix block\">\n+ <div class=\"form-group clearfix block\" data-ng-show=\"serverInfo.featureEnabled('STEP_UP_AUTHENTICATION')\">\n<label class=\"col-md-2 control-label\" for=\"newAcr\">{{:: 'acr-loa-map' | translate}}</label>\n<div class=\"col-sm-6\">\n<div class=\"input-group input-map\" ng-repeat=\"(acr, loa) in acrLoaMap\">\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Introduce profile 'feature' for step-up authentication enabled by default Closes #10315