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,317
01.12.2019 23:14:32
-10,800
bb156fb2fd118e4e49df2db78d0116009b733851
Fix minor warnings with modificators in packages: authentication, authorization, keys, partialimport, protocol from module "services"
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticator.java", "diff": "@@ -137,13 +137,13 @@ public abstract class AbstractX509ClientCertificateAuthenticator implements Auth\nreturn null;\n};\n- private static final Function<X509Certificate[], String> getSerialnumberFunc(X509AuthenticatorConfigModel config) {\n+ private static Function<X509Certificate[], String> getSerialnumberFunc(X509AuthenticatorConfigModel config) {\nreturn config.isSerialnumberHex() ?\ncerts -> Hex.toHexString(certs[0].getSerialNumber().toByteArray()) :\ncerts -> certs[0].getSerialNumber().toString();\n}\n- private static final Function<X509Certificate[], String> getIssuerDNFunc(X509AuthenticatorConfigModel config) {\n+ private static Function<X509Certificate[], String> getIssuerDNFunc(X509AuthenticatorConfigModel config) {\nreturn config.isCanonicalDnEnabled() ?\ncerts -> certs[0].getIssuerX500Principal().getName(X500Principal.CANONICAL) :\ncerts -> certs[0].getIssuerDN().getName();\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/CertificateValidator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/CertificateValidator.java", "diff": "@@ -136,7 +136,7 @@ public class CertificateValidator {\n}\n}\n- public static abstract class OCSPChecker {\n+ public abstract static class OCSPChecker {\n/**\n* Requests certificate revocation status using OCSP. The OCSP responder URI\n* is obtained from the certificate's AIA extension.\n@@ -147,7 +147,7 @@ public class CertificateValidator {\npublic abstract OCSPUtils.OCSPRevocationStatus check(X509Certificate cert, X509Certificate issuerCertificate) throws CertPathValidatorException;\n}\n- public static abstract class CRLLoaderImpl {\n+ public abstract static class CRLLoaderImpl {\n/**\n* Returns a collection of {@link X509CRL}\n* @return\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/X509AuthenticatorConfigModel.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/X509AuthenticatorConfigModel.java", "diff": "@@ -70,7 +70,7 @@ public class X509AuthenticatorConfigModel extends AuthenticatorConfigModel {\nthis.name = name;\n}\npublic String getName() { return this.name; }\n- static public MappingSourceType parse(String name) throws IllegalArgumentException, IndexOutOfBoundsException {\n+ public static MappingSourceType parse(String name) throws IllegalArgumentException, IndexOutOfBoundsException {\nif (name == null || name.trim().length() == 0)\nthrow new IllegalArgumentException(\"name\");\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/partialimport/PartialImport.java", "new_path": "services/src/main/java/org/keycloak/partialimport/PartialImport.java", "diff": "@@ -38,7 +38,7 @@ public interface PartialImport<T> {\n* @throws ErrorResponseException If the PartialImport can not be performed,\n* throw this exception.\n*/\n- public void prepare(PartialImportRepresentation rep,\n+ void prepare(PartialImportRepresentation rep,\nRealmModel realm,\nKeycloakSession session) throws ErrorResponseException;\n@@ -52,7 +52,7 @@ public interface PartialImport<T> {\n* @param realm Realm to be imported into.\n* @param session The KeycloakSession\n*/\n- public void removeOverwrites(RealmModel realm, KeycloakSession session);\n+ void removeOverwrites(RealmModel realm, KeycloakSession session);\n/**\n* Create (or re-create) all the imported resources.\n@@ -63,7 +63,7 @@ public interface PartialImport<T> {\n* @return The final results of the PartialImport request.\n* @throws ErrorResponseException if an error was detected trying to doImport a resource.\n*/\n- public PartialImportResults doImport(PartialImportRepresentation rep,\n+ PartialImportResults doImport(PartialImportRepresentation rep,\nRealmModel realm,\nKeycloakSession session) throws ErrorResponseException;\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/docker/installation/compose/DockerCertFileUtils.java", "new_path": "services/src/main/java/org/keycloak/protocol/docker/installation/compose/DockerCertFileUtils.java", "diff": "@@ -11,7 +11,7 @@ public final class DockerCertFileUtils {\npublic static final String END_CERT = \"-----END CERTIFICATE-----\";\npublic static final String BEGIN_PRIVATE_KEY = \"-----BEGIN PRIVATE KEY-----\";\npublic static final String END_PRIVATE_KEY = \"-----END PRIVATE KEY-----\";\n- public final static String LINE_SEPERATOR = System.getProperty(\"line.separator\");\n+ public static final String LINE_SEPERATOR = System.getProperty(\"line.separator\");\nprivate DockerCertFileUtils() {\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/saml/SamlProtocol.java", "new_path": "services/src/main/java/org/keycloak/protocol/saml/SamlProtocol.java", "diff": "@@ -509,8 +509,8 @@ public class SamlProtocol implements LoginProtocol {\n}\npublic static class ProtocolMapperProcessor<T> {\n- final public T mapper;\n- final public ProtocolMapperModel model;\n+ public final T mapper;\n+ public final ProtocolMapperModel model;\npublic ProtocolMapperProcessor(T mapper, ProtocolMapperModel model) {\nthis.mapper = mapper;\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/saml/mappers/SAMLGroupNameMapper.java", "new_path": "services/src/main/java/org/keycloak/protocol/saml/mappers/SAMLGroupNameMapper.java", "diff": "@@ -25,5 +25,5 @@ import org.keycloak.models.ProtocolMapperModel;\n* @version $Revision: 1 $\n*/\npublic interface SAMLGroupNameMapper {\n- public String mapName(ProtocolMapperModel model, GroupModel group);\n+ String mapName(ProtocolMapperModel model, GroupModel group);\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/protocol/saml/mappers/SAMLRoleNameMapper.java", "new_path": "services/src/main/java/org/keycloak/protocol/saml/mappers/SAMLRoleNameMapper.java", "diff": "@@ -25,5 +25,5 @@ import org.keycloak.models.RoleModel;\n* @version $Revision: 1 $\n*/\npublic interface SAMLRoleNameMapper {\n- public String mapName(ProtocolMapperModel model, RoleModel role);\n+ String mapName(ProtocolMapperModel model, RoleModel role);\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12317 Fix minor warnings with modificators in packages: authentication, authorization, keys, partialimport, protocol from module "services"
339,317
29.11.2019 22:29:17
-10,800
697eaa4f3670ffcd17b64abccd9b5a4272982998
Fix warnings with collections in packages: authentification, authorization, broker, email, events, exportimport from module "services"
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/challenge/BasicAuthAuthenticatorFactory.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/challenge/BasicAuthAuthenticatorFactory.java", "diff": "@@ -89,7 +89,7 @@ public class BasicAuthAuthenticatorFactory implements AuthenticatorFactory {\n@Override\npublic List<ProviderConfigProperty> getConfigProperties() {\n- return Collections.EMPTY_LIST;\n+ return Collections.emptyList();\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/challenge/BasicAuthOTPAuthenticatorFactory.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/challenge/BasicAuthOTPAuthenticatorFactory.java", "diff": "@@ -89,7 +89,7 @@ public class BasicAuthOTPAuthenticatorFactory implements AuthenticatorFactory {\n@Override\npublic List<ProviderConfigProperty> getConfigProperties() {\n- return Collections.EMPTY_LIST;\n+ return Collections.emptyList();\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/challenge/NoCookieFlowRedirectAuthenticatorFactory.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/challenge/NoCookieFlowRedirectAuthenticatorFactory.java", "diff": "@@ -92,7 +92,7 @@ public class NoCookieFlowRedirectAuthenticatorFactory implements AuthenticatorFa\n@Override\npublic List<ProviderConfigProperty> getConfigProperties() {\n- return Collections.EMPTY_LIST;\n+ return Collections.emptyList();\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticatorFactory.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticatorFactory.java", "diff": "package org.keycloak.authentication.authenticators.x509;\n+import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n@@ -89,9 +90,7 @@ public abstract class AbstractX509ClientCertificateAuthenticatorFactory implemen\nprotected static final List<ProviderConfigProperty> configProperties;\nstatic {\nList<String> mappingSourceTypes = new LinkedList<>();\n- for (String s : mappingSources) {\n- mappingSourceTypes.add(s);\n- }\n+ Collections.addAll(mappingSourceTypes, mappingSources);\nProviderConfigProperty mappingMethodList = new ProviderConfigProperty();\nmappingMethodList.setType(ProviderConfigProperty.LIST_TYPE);\nmappingMethodList.setName(MAPPING_SOURCE_SELECTION);\n@@ -123,9 +122,7 @@ public abstract class AbstractX509ClientCertificateAuthenticatorFactory implemen\nregExp.setHelpText(\"The regular expression to extract a user identity. The expression must contain a single group. For example, 'uniqueId=(.*?)(?:,|$)' will match '[email protected], CN=somebody' and give [email protected]\");\nList<String> mapperTypes = new LinkedList<>();\n- for (String m : userModelMappers) {\n- mapperTypes.add(m);\n- }\n+ Collections.addAll(mapperTypes, userModelMappers);\nProviderConfigProperty userMapperList = new ProviderConfigProperty();\nuserMapperList.setType(ProviderConfigProperty.LIST_TYPE);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateDirectGrantAuthenticator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateDirectGrantAuthenticator.java", "diff": "@@ -35,7 +35,7 @@ import java.util.Map;\npublic abstract class AbstractX509ClientCertificateDirectGrantAuthenticator extends AbstractX509ClientCertificateAuthenticator {\npublic Response errorResponse(int status, String error, String errorDescription) {\n- Map<String, String> e = new HashMap<String, String>();\n+ Map<String, String> e = new HashMap<>();\ne.put(OAuth2Constants.ERROR, error);\nif (errorDescription != null) {\ne.put(OAuth2Constants.ERROR_DESCRIPTION, errorDescription);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authorization/admin/PolicyEvaluationService.java", "new_path": "services/src/main/java/org/keycloak/authorization/admin/PolicyEvaluationService.java", "diff": "@@ -21,6 +21,7 @@ package org.keycloak.authorization.admin;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\n+import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\n@@ -104,11 +105,8 @@ public class PolicyEvaluationService {\nif (givenAttributes != null) {\ngivenAttributes.forEach((key, entryValue) -> {\nif (entryValue != null) {\n- List<String> values = new ArrayList();\n-\n- for (String value : entryValue.split(\",\")) {\n- values.add(value);\n- }\n+ List<String> values = new ArrayList<>();\n+ Collections.addAll(values, entryValue.split(\",\"));\nclaims.put(key, values);\n}\n@@ -140,11 +138,8 @@ public class PolicyEvaluationService {\nif (givenAttributes != null) {\ngivenAttributes.forEach((key, entryValue) -> {\nif (entryValue != null) {\n- List<String> values = new ArrayList();\n-\n- for (String value : entryValue.split(\",\")) {\n- values.add(value);\n- }\n+ List<String> values = new ArrayList<>();\n+ Collections.addAll(values, entryValue.split(\",\"));\nattributes.put(key, values);\n}\n@@ -166,7 +161,7 @@ public class PolicyEvaluationService {\nSet<ScopeRepresentation> givenScopes = resource.getScopes();\nif (givenScopes == null) {\n- givenScopes = new HashSet();\n+ givenScopes = new HashSet<>();\n}\nScopeStore scopeStore = storeFactory.getScopeStore();\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authorization/protection/permission/PermissionTicketService.java", "new_path": "services/src/main/java/org/keycloak/authorization/protection/permission/PermissionTicketService.java", "diff": "@@ -116,7 +116,7 @@ public class PermissionTicketService {\nif (!match)\nthrow new ErrorResponseException(\"invalid_resource_id\", \"Resource set with id [\" + representation.getResource() + \"] does not have Scope [\" + scope.getName() + \"]\", Response.Status.BAD_REQUEST);\n- Map<String, String> attributes = new HashMap<String, String>();\n+ Map<String, String> attributes = new HashMap<>();\nattributes.put(PermissionTicket.RESOURCE, resource.getId());\nattributes.put(PermissionTicket.SCOPE, scope.getId());\nattributes.put(PermissionTicket.REQUESTER, user.getId());\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/broker/saml/SAMLIdentityProviderFactory.java", "new_path": "services/src/main/java/org/keycloak/broker/saml/SAMLIdentityProviderFactory.java", "diff": "@@ -155,7 +155,7 @@ public class SAMLIdentityProviderFactory extends AbstractIdentityProviderFactory\nthrow new RuntimeException(\"Could not parse IdP SAML Metadata\", pe);\n}\n- return new HashMap<String, String>();\n+ return new HashMap<>();\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "new_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "diff": "@@ -104,7 +104,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\n@Override\npublic void sendEvent(Event event) throws EmailException {\n- Map<String, Object> attributes = new HashMap<String, Object>();\n+ Map<String, Object> attributes = new HashMap<>();\nattributes.put(\"user\", new ProfileBean(user));\nattributes.put(\"event\", new EventBean(event));\n@@ -113,7 +113,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\n@Override\npublic void sendPasswordReset(String link, long expirationInMinutes) throws EmailException {\n- Map<String, Object> attributes = new HashMap<String, Object>(this.attributes);\n+ Map<String, Object> attributes = new HashMap<>(this.attributes);\nattributes.put(\"user\", new ProfileBean(user));\naddLinkInfoIntoAttributes(link, expirationInMinutes, attributes);\n@@ -127,7 +127,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\nsetRealm(session.getContext().getRealm());\nsetUser(user);\n- Map<String, Object> attributes = new HashMap<String, Object>(this.attributes);\n+ Map<String, Object> attributes = new HashMap<>(this.attributes);\nattributes.put(\"user\", new ProfileBean(user));\nattributes.put(\"realmName\", realm.getName());\n@@ -137,7 +137,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\n@Override\npublic void sendConfirmIdentityBrokerLink(String link, long expirationInMinutes) throws EmailException {\n- Map<String, Object> attributes = new HashMap<String, Object>(this.attributes);\n+ Map<String, Object> attributes = new HashMap<>(this.attributes);\nattributes.put(\"user\", new ProfileBean(user));\naddLinkInfoIntoAttributes(link, expirationInMinutes, attributes);\n@@ -150,13 +150,13 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\nattributes.put(\"identityProviderContext\", brokerContext);\nattributes.put(\"identityProviderAlias\", idpAlias);\n- List<Object> subjectAttrs = Arrays.<Object> asList(idpAlias);\n+ List<Object> subjectAttrs = Arrays.asList(idpAlias);\nsend(\"identityProviderLinkSubject\", subjectAttrs, \"identity-provider-link.ftl\", attributes);\n}\n@Override\npublic void sendExecuteActions(String link, long expirationInMinutes) throws EmailException {\n- Map<String, Object> attributes = new HashMap<String, Object>(this.attributes);\n+ Map<String, Object> attributes = new HashMap<>(this.attributes);\nattributes.put(\"user\", new ProfileBean(user));\naddLinkInfoIntoAttributes(link, expirationInMinutes, attributes);\n@@ -167,7 +167,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\n@Override\npublic void sendVerifyEmail(String link, long expirationInMinutes) throws EmailException {\n- Map<String, Object> attributes = new HashMap<String, Object>(this.attributes);\n+ Map<String, Object> attributes = new HashMap<>(this.attributes);\nattributes.put(\"user\", new ProfileBean(user));\naddLinkInfoIntoAttributes(link, expirationInMinutes, attributes);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/events/email/EmailEventListenerProviderFactory.java", "new_path": "services/src/main/java/org/keycloak/events/email/EmailEventListenerProviderFactory.java", "diff": "@@ -34,12 +34,12 @@ import java.util.Set;\n*/\npublic class EmailEventListenerProviderFactory implements EventListenerProviderFactory {\n- private static final Set<EventType> SUPPORTED_EVENTS = new HashSet<EventType>();\n+ private static final Set<EventType> SUPPORTED_EVENTS = new HashSet<>();\nstatic {\nCollections.addAll(SUPPORTED_EVENTS, EventType.LOGIN_ERROR, EventType.UPDATE_PASSWORD, EventType.REMOVE_TOTP, EventType.UPDATE_TOTP);\n}\n- private Set<EventType> includedEvents = new HashSet<EventType>();\n+ private Set<EventType> includedEvents = new HashSet<>();\n@Override\npublic EventListenerProvider create(KeycloakSession session) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/exportimport/dir/DirImportProvider.java", "new_path": "services/src/main/java/org/keycloak/exportimport/dir/DirImportProvider.java", "diff": "@@ -95,7 +95,7 @@ public class DirImportProvider implements ImportProvider {\n}\n});\n- List<String> realmNames = new ArrayList<String>();\n+ List<String> realmNames = new ArrayList<>();\nfor (File file : realmFiles) {\nString fileName = file.getName();\n// Parse \"foo\" from \"foo-realm.json\"\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/exportimport/singlefile/SingleFileExportProvider.java", "new_path": "services/src/main/java/org/keycloak/exportimport/singlefile/SingleFileExportProvider.java", "diff": "@@ -60,7 +60,7 @@ public class SingleFileExportProvider implements ExportProvider {\n@Override\nprotected void runExportImportTask(KeycloakSession session) throws IOException {\nList<RealmModel> realms = session.realms().getRealms();\n- List<RealmRepresentation> reps = new ArrayList<RealmRepresentation>();\n+ List<RealmRepresentation> reps = new ArrayList<>();\nfor (RealmModel realm : realms) {\nreps.add(ExportUtils.exportRealm(session, realm, true, true));\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": "@@ -410,7 +410,7 @@ public class ExportUtils {\n}\npublic static List<String> getRoleNames(Collection<RoleModel> roles) {\n- List<String> roleNames = new ArrayList<String>();\n+ List<String> roleNames = new ArrayList<>();\nfor (RoleModel role : roles) {\nroleNames.add(role.getName());\n}\n@@ -479,7 +479,7 @@ public class ExportUtils {\n// Social links\nSet<FederatedIdentityModel> socialLinks = session.users().getFederatedIdentities(user, realm);\n- List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<FederatedIdentityRepresentation>();\n+ List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<>();\nfor (FederatedIdentityModel socialLink : socialLinks) {\nFederatedIdentityRepresentation socialLinkRep = exportSocialLink(socialLink);\nsocialLinkReps.add(socialLinkRep);\n@@ -517,7 +517,7 @@ public class ExportUtils {\n// Credentials\nList<CredentialModel> creds = session.userCredentialManager().getStoredCredentials(realm, user);\n- List<CredentialRepresentation> credReps = new ArrayList<CredentialRepresentation>();\n+ List<CredentialRepresentation> credReps = new ArrayList<>();\nfor (CredentialModel cred : creds) {\nCredentialRepresentation credRep = exportCredential(cred);\ncredReps.add(credRep);\n@@ -527,7 +527,7 @@ public class ExportUtils {\n// Grants\nList<UserConsentModel> consents = session.users().getConsents(realm, user.getId());\n- LinkedList<UserConsentRepresentation> consentReps = new LinkedList<UserConsentRepresentation>();\n+ LinkedList<UserConsentRepresentation> consentReps = new LinkedList<>();\nfor (UserConsentModel consent : consents) {\nUserConsentRepresentation consentRep = ModelToRepresentation.toRepresentation(consent);\nconsentReps.add(consentRep);\n@@ -657,7 +657,7 @@ public class ExportUtils {\n// Social links\nSet<FederatedIdentityModel> socialLinks = session.userFederatedStorage().getFederatedIdentities(id, realm);\n- List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<FederatedIdentityRepresentation>();\n+ List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<>();\nfor (FederatedIdentityModel socialLink : socialLinks) {\nFederatedIdentityRepresentation socialLinkRep = exportSocialLink(socialLink);\nsocialLinkReps.add(socialLinkRep);\n@@ -697,7 +697,7 @@ public class ExportUtils {\n// Credentials\nList<CredentialModel> creds = session.userFederatedStorage().getStoredCredentials(realm, id);\n- List<CredentialRepresentation> credReps = new ArrayList<CredentialRepresentation>();\n+ List<CredentialRepresentation> credReps = new ArrayList<>();\nfor (CredentialModel cred : creds) {\nCredentialRepresentation credRep = exportCredential(cred);\ncredReps.add(credRep);\n@@ -706,7 +706,7 @@ public class ExportUtils {\n// Grants\nList<UserConsentModel> consents = session.users().getConsents(realm, id);\n- LinkedList<UserConsentRepresentation> consentReps = new LinkedList<UserConsentRepresentation>();\n+ LinkedList<UserConsentRepresentation> consentReps = new LinkedList<>();\nfor (UserConsentModel consent : consents) {\nUserConsentRepresentation consentRep = ModelToRepresentation.toRepresentation(consent);\nconsentReps.add(consentRep);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12309 Fix warnings with collections in packages: authentification, authorization, broker, email, events, exportimport from module "services"
339,317
07.12.2019 21:58:38
-10,800
aceb123242c60d608e5247d73169143b753d6779
Fix minor warnings in tests from module "services"
[ { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/connections/httpclient/DefaultHttpClientFactoryTest.java", "new_path": "services/src/test/java/org/keycloak/connections/httpclient/DefaultHttpClientFactoryTest.java", "diff": "@@ -32,7 +32,6 @@ import javax.net.ssl.SSLPeerUnverifiedException;\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.http.HttpStatus;\n-import org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\n@@ -52,7 +51,7 @@ public class DefaultHttpClientFactoryTest {\nprivate static final String TEST_DOMAIN = \"www.google.com\";\n@Test\n- public void createHttpClientProviderWithDisableTrustManager() throws ClientProtocolException, IOException{\n+ public void createHttpClientProviderWithDisableTrustManager() throws IOException{\nMap<String, String> values = new HashMap<>();\nvalues.put(DISABLE_TRUST_MANAGER_PROPERTY, \"true\");\nDefaultHttpClientFactory factory = new DefaultHttpClientFactory();\n@@ -69,7 +68,7 @@ public class DefaultHttpClientFactoryTest {\n}\n@Test(expected = SSLPeerUnverifiedException.class)\n- public void createHttpClientProviderWithUnvailableURL() throws ClientProtocolException, IOException {\n+ public void createHttpClientProviderWithUnvailableURL() throws IOException {\nDefaultHttpClientFactory factory = new DefaultHttpClientFactory();\nfactory.init(scope(new HashMap<>()));\nKeycloakSession session = new DefaultKeycloakSession(new DefaultKeycloakSessionFactory());\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/social/openshift/OpenshiftV3IdentityProviderTest.java", "new_path": "services/src/test/java/org/keycloak/social/openshift/OpenshiftV3IdentityProviderTest.java", "diff": "@@ -7,7 +7,7 @@ import org.keycloak.models.IdentityProviderModel;\npublic class OpenshiftV3IdentityProviderTest {\n@Test\n- public void shouldConstructProviderUrls() throws Exception {\n+ public void shouldConstructProviderUrls() {\nfinal OpenshiftV3IdentityProviderConfig config = new OpenshiftV3IdentityProviderConfig(new IdentityProviderModel());\nconfig.setBaseUrl(\"http://openshift.io:8443\");\nfinal OpenshiftV3IdentityProvider openshiftV3IdentityProvider = new OpenshiftV3IdentityProvider(null, config);\n@@ -16,7 +16,7 @@ public class OpenshiftV3IdentityProviderTest {\n}\n@Test\n- public void shouldConstructProviderUrlsForBaseUrlWithTrailingSlash() throws Exception {\n+ public void shouldConstructProviderUrlsForBaseUrlWithTrailingSlash() {\nfinal OpenshiftV3IdentityProviderConfig config = new OpenshiftV3IdentityProviderConfig(new IdentityProviderModel());\nconfig.setBaseUrl(\"http://openshift.io:8443/\");\nfinal OpenshiftV3IdentityProvider openshiftV3IdentityProvider = new OpenshiftV3IdentityProvider(null, config);\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/social/openshift/OpenshiftV4IdentityProviderTest.java", "new_path": "services/src/test/java/org/keycloak/social/openshift/OpenshiftV4IdentityProviderTest.java", "diff": "@@ -11,7 +11,6 @@ import org.keycloak.models.IdentityProviderModel;\nimport org.keycloak.models.KeycloakSession;\nimport java.io.ByteArrayInputStream;\n-import java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.util.HashMap;\n@@ -35,7 +34,7 @@ public class OpenshiftV4IdentityProviderTest {\n}\n@Test\n- public void testExtractingConfigProperties() throws IOException {\n+ public void testExtractingConfigProperties() {\n//given\nOpenshiftV4IdentityProviderConfig config = new OpenshiftV4IdentityProviderConfig(new IdentityProviderModel());\n@@ -54,7 +53,7 @@ public class OpenshiftV4IdentityProviderTest {\n}\n@Test\n- public void testHttpClientErrors() throws IOException {\n+ public void testHttpClientErrors() {\n//given\nOpenshiftV4IdentityProviderConfig config = new OpenshiftV4IdentityProviderConfig(new IdentityProviderModel());\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/test/broker/oidc/mappers/AbstractJsonUserAttributeMapperTest.java", "new_path": "services/src/test/java/org/keycloak/test/broker/oidc/mappers/AbstractJsonUserAttributeMapperTest.java", "diff": "*/\npackage org.keycloak.test.broker.oidc.mappers;\n-import com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport org.junit.Assert;\n@@ -56,16 +55,16 @@ public class AbstractJsonUserAttributeMapperTest {\n}\n@Test\n- public void getJsonValue_simpleValues() throws JsonProcessingException, IOException {\n+ public void getJsonValue_simpleValues() throws IOException {\n//unknown field returns null\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_unknown\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_unknown\"));\n// we check value is trimmed also!\nAssert.assertEquals(\"v1\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value1\"));\n// test for KEYCLOAK-4202 bug (null value handling)\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_null\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_empty\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_null\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_empty\"));\nAssert.assertEquals(\"true\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_b\"));\nAssert.assertEquals(\"454\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_i\"));\n@@ -75,7 +74,7 @@ public class AbstractJsonUserAttributeMapperTest {\n}\n@Test\n- public void getJsonValue_nestedSimpleValues() throws JsonProcessingException, IOException {\n+ public void getJsonValue_nestedSimpleValues() throws IOException {\n// JsonNode if path points to JSON object\nAssert.assertEquals(mapper.readTree(\"{\\n\"\n+ \" \\\"value1\\\": \\\" fgh \\\",\\n\"\n@@ -93,14 +92,14 @@ public class AbstractJsonUserAttributeMapperTest {\nAssert.assertEquals(mapper.readTree(\"{\\\"av1\\\": \\\"vala1\\\"}\"), AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[0]\"));\n//unknown field returns null\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.value_unknown\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.nest2.value_unknown\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.value_unknown\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.nest2.value_unknown\"));\n// we check value is trimmed also!\nAssert.assertEquals(\"fgh\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.value1\"));\n// test for KEYCLOAK-4202 bug (null value handling)\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.value_null\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.value_empty\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.value_null\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.value_empty\"));\nAssert.assertEquals(\"false\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.nest2.value_b\"));\nAssert.assertEquals(\"43\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nest1.nest2.value_i\"));\n@@ -111,12 +110,12 @@ public class AbstractJsonUserAttributeMapperTest {\n}\n@Test\n- public void getJsonValue_simpleArray() throws JsonProcessingException, IOException {\n+ public void getJsonValue_simpleArray() throws IOException {\n// array field itself returns null if no index is provided\nAssert.assertEquals(Arrays.asList(\"a1\", \"a2\"), AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_array\"));\n// outside index returns null\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_array[2]\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_array[2]\"));\n//corect index\nAssert.assertEquals(\"a1\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"value_array[0]\"));\n@@ -131,18 +130,18 @@ public class AbstractJsonUserAttributeMapperTest {\n}\n@Test\n- public void getJsonValue_nestedArrayWithObjects() throws JsonProcessingException, IOException {\n+ public void getJsonValue_nestedArrayWithObjects() throws IOException {\nAssert.assertEquals(\"vala1\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[0].av1\"));\nAssert.assertEquals(\"vala2\", AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[1].av1\"));\n//different path erros or nonexisting indexes or fields return null\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[2].av1\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[0].av_unknown\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[].av1\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a.av1\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a].av1\"));\n- Assert.assertEquals(null, AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[.av1\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[2].av1\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[0].av_unknown\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[].av1\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a.av1\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a].av1\"));\n+ Assert.assertNull(AbstractJsonUserAttributeMapper.getJsonValue(getJsonNode(), \"nesta.a[.av1\"));\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/test/broker/saml/SAMLDataMarshallerTest.java", "new_path": "services/src/test/java/org/keycloak/test/broker/saml/SAMLDataMarshallerTest.java", "diff": "@@ -45,15 +45,15 @@ public class SAMLDataMarshallerTest {\nprivate static final String TEST_AUTHN_TYPE = \"<saml:AuthnStatement xmlns:saml=\\\"urn:oasis:names:tc:SAML:2.0:assertion\\\" xmlns=\\\"urn:oasis:names:tc:SAML:2.0:assertion\\\" AuthnInstant=\\\"2015-11-06T11:00:33.923Z\\\" SessionIndex=\\\"fa0f4fd3-8a11-44f4-9acb-ee30c5bb8fe5\\\"><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement>\";\n@Test\n- public void testParseResponse() throws Exception {\n+ public void testParseResponse() {\nSAMLDataMarshaller serializer = new SAMLDataMarshaller();\nResponseType responseType = serializer.deserialize(TEST_RESPONSE, ResponseType.class);\n// test ResponseType\n- Assert.assertEquals(responseType.getID(), \"ID_4804cf50-cd96-4b92-823e-89adaa0c78ba\");\n- Assert.assertEquals(responseType.getDestination(), \"http://localhost:8081/auth/realms/realm-with-broker/broker/kc-saml-idp-basic/endpoint\");\n- Assert.assertEquals(responseType.getIssuer().getValue(), \"http://localhost:8082/auth/realms/realm-with-saml-idp-basic\");\n- Assert.assertEquals(responseType.getAssertions().get(0).getID(), \"ID_29b196c2-d641-45c8-a423-8ed8e54d4cf9\");\n+ Assert.assertEquals(\"ID_4804cf50-cd96-4b92-823e-89adaa0c78ba\", responseType.getID());\n+ Assert.assertEquals(\"http://localhost:8081/auth/realms/realm-with-broker/broker/kc-saml-idp-basic/endpoint\", responseType.getDestination());\n+ Assert.assertEquals(\"http://localhost:8082/auth/realms/realm-with-saml-idp-basic\", responseType.getIssuer().getValue());\n+ Assert.assertEquals(\"ID_29b196c2-d641-45c8-a423-8ed8e54d4cf9\", responseType.getAssertions().get(0).getID());\n// back to String\nString serialized = serializer.serialize(responseType);\n@@ -61,13 +61,13 @@ public class SAMLDataMarshallerTest {\n}\n@Test\n- public void testParseAssertion() throws Exception {\n+ public void testParseAssertion() {\nSAMLDataMarshaller serializer = new SAMLDataMarshaller();\nAssertionType assertion = serializer.deserialize(TEST_ASSERTION, AssertionType.class);\n// test assertion\n- Assert.assertEquals(assertion.getID(), \"ID_29b196c2-d641-45c8-a423-8ed8e54d4cf9\");\n- Assert.assertEquals(((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue(), \"test-user\");\n+ Assert.assertEquals(\"ID_29b196c2-d641-45c8-a423-8ed8e54d4cf9\", assertion.getID());\n+ Assert.assertEquals(\"test-user\", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());\n// back to String\nString serialized = serializer.serialize(assertion);\n@@ -75,13 +75,13 @@ public class SAMLDataMarshallerTest {\n}\n@Test\n- public void testParseAssertionWitNameId() throws Exception {\n+ public void testParseAssertionWitNameId() {\nSAMLDataMarshaller serializer = new SAMLDataMarshaller();\nAssertionType assertion = serializer.deserialize(TEST_ASSERTION_WITH_NAME_ID, AssertionType.class);\n// test assertion\n- Assert.assertEquals(assertion.getID(), \"ID_29b196c2-d641-45c8-a423-8ed8e54d4cf9\");\n- Assert.assertEquals(((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue(), \"test-user\");\n+ Assert.assertEquals(\"ID_29b196c2-d641-45c8-a423-8ed8e54d4cf9\", assertion.getID());\n+ Assert.assertEquals(\"test-user\", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());\n// back to String\nString serialized = serializer.serialize(assertion);\n@@ -89,12 +89,12 @@ public class SAMLDataMarshallerTest {\n}\n@Test\n- public void testParseAuthnType() throws Exception {\n+ public void testParseAuthnType() {\nSAMLDataMarshaller serializer = new SAMLDataMarshaller();\nAuthnStatementType authnStatement = serializer.deserialize(TEST_AUTHN_TYPE, AuthnStatementType.class);\n// test authnStatement\n- Assert.assertEquals(authnStatement.getSessionIndex(), \"fa0f4fd3-8a11-44f4-9acb-ee30c5bb8fe5\");\n+ Assert.assertEquals(\"fa0f4fd3-8a11-44f4-9acb-ee30c5bb8fe5\", authnStatement.getSessionIndex());\n// back to String\nString serialized = serializer.serialize(authnStatement);\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/test/broker/saml/SAMLParsingTest.java", "new_path": "services/src/test/java/org/keycloak/test/broker/saml/SAMLParsingTest.java", "diff": "@@ -33,7 +33,7 @@ public class SAMLParsingTest {\nprivate static final String SAML_RESPONSE = \"PHNhbWxwOkxvZ291dFJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiIHhtbG5zPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIiBEZXN0aW5hdGlvbj0iaHR0cDovL2xvY2FsaG9zdDo4MDgxL2F1dGgvcmVhbG1zL3JlYWxtLXdpdGgtYnJva2VyL2Jyb2tlci9rYy1zYW1sLWlkcC1iYXNpYy9lbmRwb2ludCIgSUQ9IklEXzlhMTcxZDIzLWM0MTctNDJmNS05YmNhLWMwOTMxMjNmZDY4YyIgSW5SZXNwb25zZVRvPSJJRF9iYzczMDcxMS0yMDM3LTQzZjMtYWQ3Ni03YmMzMzg0MmZiODciIElzc3VlSW5zdGFudD0iMjAxNi0wMi0yOVQxMjowMDoxNC4wNDRaIiBWZXJzaW9uPSIyLjAiPjxzYW1sOklzc3VlciB4bWxuczpzYW1sPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIj5odHRwOi8vbG9jYWxob3N0OjgwODIvYXV0aC9yZWFsbXMvcmVhbG0td2l0aC1zYW1sLWlkcC1iYXNpYzwvc2FtbDpJc3N1ZXI+PHNhbWxwOlN0YXR1cz48c2FtbHA6U3RhdHVzQ29kZSBWYWx1ZT0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnN0YXR1czpTdWNjZXNzIi8+PC9zYW1scDpTdGF0dXM+PC9zYW1scDpMb2dvdXRSZXNwb25zZT4=\";\n@Test\n- public void parseTest() throws Exception {\n+ public void parseTest() {\nbyte[] samlBytes = PostBindingUtil.base64Decode(SAML_RESPONSE);\nSAMLDocumentHolder holder = SAMLRequestParser.parseResponseDocument(samlBytes);\nAssert.assertNotNull(holder);\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/vault/VaultTranscriberTest.java", "new_path": "services/src/test/java/org/keycloak/vault/VaultTranscriberTest.java", "diff": "@@ -66,10 +66,9 @@ public class VaultTranscriberTest {\n* the try-wih-resources block. For the latter, the tests checks if an empty {@link Optional} has been returned by the\n* transcriber.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetRawSecretUsingValidExpressions() throws Exception {\n+ public void testGetRawSecretUsingValidExpressions() {\nByteBuffer secretBuffer = null;\nbyte[] secretArray = null;\n@@ -107,10 +106,9 @@ public class VaultTranscriberTest {\n* checks if the returned secret matches the specified values (using both the buffer and array representation of the value)\n* and then checks if the secrets have been overridden/destroyed after the try-wih-resources block.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetRawSecretUsingInvalidExpressions() throws Exception {\n+ public void testGetRawSecretUsingInvalidExpressions() {\nByteBuffer secretBuffer;\nbyte[] secretArray;\n@@ -137,10 +135,9 @@ public class VaultTranscriberTest {\n/**\n* Tests that a null vault expression always returns an empty secret.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetRawSecretUsingNullExpression() throws Exception {\n+ public void testGetRawSecretUsingNullExpression() {\n// check that a null expression results in an empty optional instance.\ntry (VaultRawSecret secret = transcriber.getRawSecret(null)) {\nAssert.assertFalse(secret.get().isPresent());\n@@ -158,10 +155,9 @@ public class VaultTranscriberTest {\n* the try-wih-resources block. For the latter, the tests checks if an empty {@link Optional} has been returned by the\n* transcriber.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetCharSecretUsingValidExpressions() throws Exception {\n+ public void testGetCharSecretUsingValidExpressions() {\nCharBuffer secretBuffer = null;\nchar[] secretArray = null;\n@@ -199,10 +195,9 @@ public class VaultTranscriberTest {\n* checks if the returned secret matches the specified values (using both the buffer and array representation of the value)\n* and then checks if the secrets have been overridden/destroyed after the try-wih-resources block.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetCharSecretUsingInvalidExpressions() throws Exception {\n+ public void testGetCharSecretUsingInvalidExpressions() {\nCharBuffer secretBuffer;\nchar[] secretArray;\n@@ -229,10 +224,9 @@ public class VaultTranscriberTest {\n/**\n* Tests that a null vault expression always returns an empty secret.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetCharSecretUsingNullExpression() throws Exception {\n+ public void testGetCharSecretUsingNullExpression() {\n// check that a null expression results in an empty optional instance.\ntry (VaultCharSecret secret = transcriber.getCharSecret(null)) {\nAssert.assertFalse(secret.get().isPresent());\n@@ -249,10 +243,9 @@ public class VaultTranscriberTest {\n* the tests checks if an empty {@link Optional} has been returned by the transcriber. Because strings are immutable,\n* this test doesn't verify if the secrets have been destroyed after the try-with-resources block.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetStringSecretUsingValidExpressions() throws Exception {\n+ public void testGetStringSecretUsingValidExpressions() {\n// attempt to obtain a secret using a proper vault expressions. The key may or may not exist in the vault, so we\n// check both cases using the returned optional and comparing against the expected secret.\n@@ -278,10 +271,9 @@ public class VaultTranscriberTest {\n* checks if the returned secret matches the specified values. Again, due to the fact that strings are immutable, this test\n* doesn't verify if the secrets have been destroyed after the try-with-resources block.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetStringSecretUsingInvalidExpressions() throws Exception {\n+ public void testGetStringSecretUsingInvalidExpressions() {\n// attempt to obtain a secret using invalid vault expressions - the value itself should be returned as a byte buffer.\nfor (String value : invalidExpressions) {\n@@ -297,10 +289,9 @@ public class VaultTranscriberTest {\n/**\n* Tests that a null vault expression always returns an empty secret.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testGetStringSecretUsingNullExpression() throws Exception {\n+ public void testGetStringSecretUsingNullExpression() {\n// check that a null expression results in an empty optional instance.\ntry (VaultStringSecret secret = transcriber.getStringSecret(null)) {\nAssert.assertFalse(secret.get().isPresent());\n@@ -311,10 +302,9 @@ public class VaultTranscriberTest {\n* Tests that when no {@link VaultProvider} is supplied to the transcriber it uses a default implementation that\n* always returns empty secrets.\n*\n- * @throws Exception if an error occurs while running the test.\n*/\n@Test\n- public void testTranscriberWithNullProvider() throws Exception {\n+ public void testTranscriberWithNullProvider() {\nVaultTranscriber transcriber = new DefaultVaultTranscriber(null);\n// none of the valid expressions identify a key in the default vault as it always returns empty secrets.\nfor (String key : validExpressions.keySet()) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12417 Fix minor warnings in tests from module "services"
339,343
12.12.2019 10:41:17
-3,600
7a14661fce5df877c75393b9dc0a4898b50514d0
Login fails if federated user is read-only and has selected a locale on the login screen
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/locale/DefaultLocaleSelectorProvider.java", "new_path": "services/src/main/java/org/keycloak/locale/DefaultLocaleSelectorProvider.java", "diff": "*/\npackage org.keycloak.locale;\n+import org.jboss.logging.Logger;\nimport org.keycloak.OAuth2Constants;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.services.managers.AuthenticationManager;\nimport org.keycloak.services.util.CookieHelper;\n+import org.keycloak.storage.ReadOnlyException;\nimport javax.ws.rs.core.HttpHeaders;\nimport javax.ws.rs.core.UriInfo;\n@@ -29,6 +31,8 @@ import java.util.Locale;\npublic class DefaultLocaleSelectorProvider implements LocaleSelectorProvider {\n+ private static final Logger logger = Logger.getLogger(DefaultLocaleSelectorProvider.class);\n+\nprotected static final String LOCALE_COOKIE = \"KEYCLOAK_LOCALE\";\nprotected static final String KC_LOCALE_PARAM = \"kc_locale\";\n@@ -153,7 +157,11 @@ public class DefaultLocaleSelectorProvider implements LocaleSelectorProvider {\nprotected void updateUsersLocale(UserModel user, String locale) {\nif (!locale.equals(user.getFirstAttribute(\"locale\"))) {\n+ try {\nuser.setSingleAttribute(UserModel.LOCALE, locale);\n+ } catch (ReadOnlyException e) {\n+ logger.debug(\"Attempt to store 'locale' attribute to read only user model. Ignoring exception\", e);\n+ }\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-6115 Login fails if federated user is read-only and has selected a locale on the login screen
339,404
20.12.2019 08:09:55
-3,600
7409f6991f942049bd48428c4ea77a8f9770b30f
Argument 'customJacksonProvider' not being passed on
[ { "change_type": "MODIFY", "old_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/Keycloak.java", "new_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/Keycloak.java", "diff": "@@ -96,7 +96,7 @@ public class Keycloak implements AutoCloseable {\n}\npublic static Keycloak getInstance(String serverUrl, String realm, String username, String password, String clientId, String clientSecret, SSLContext sslContext, ResteasyJackson2Provider customJacksonProvider) {\n- return getInstance(serverUrl, realm, username, password, clientId, clientSecret, sslContext, null, false, null);\n+ return getInstance(serverUrl, realm, username, password, clientId, clientSecret, sslContext, customJacksonProvider, false, null);\n}\npublic static Keycloak getInstance(String serverUrl, String realm, String username, String password, String clientId) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12166 Argument 'customJacksonProvider' not being passed on
339,317
22.11.2019 00:25:29
-10,800
23b794aa51fb7406390da0e2392d95d20194113b
Remove unused method from org.keycloak.saml.common.util.DocumentUtil
[ { "change_type": "MODIFY", "old_path": "saml-core/src/main/java/org/keycloak/saml/common/util/DocumentUtil.java", "new_path": "saml-core/src/main/java/org/keycloak/saml/common/util/DocumentUtil.java", "diff": "@@ -22,7 +22,6 @@ import org.keycloak.saml.common.constants.GeneralConstants;\nimport org.keycloak.saml.common.exceptions.ConfigurationException;\nimport org.keycloak.saml.common.exceptions.ParsingException;\nimport org.keycloak.saml.common.exceptions.ProcessingException;\n-import org.w3c.dom.DOMConfiguration;\nimport org.w3c.dom.DOMException;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n@@ -40,10 +39,8 @@ import javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactoryConfigurationError;\n-import javax.xml.transform.dom.DOMResult;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n-import javax.xml.xpath.XPathException;\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\n@@ -70,26 +67,6 @@ public class DocumentUtil {\npublic static final String feature_external_parameter_entities = \"http://xml.org/sax/features/external-parameter-entities\";\npublic static final String feature_disallow_doctype_decl = \"http://apache.org/xml/features/disallow-doctype-decl\";\n- /**\n- * Check whether a node belongs to a document\n- *\n- * @param doc\n- * @param node\n- *\n- * @return\n- */\n- public static boolean containsNode(Document doc, Node node) {\n- if (node.getNodeType() == Node.ELEMENT_NODE) {\n- Element elem = (Element) node;\n- NodeList nl = doc.getElementsByTagNameNS(elem.getNamespaceURI(), elem.getLocalName());\n- if (nl != null && nl.getLength() > 0)\n- return true;\n- else\n- return false;\n- }\n- throw new UnsupportedOperationException();\n- }\n-\n/**\n* Create a new document\n*\n@@ -241,32 +218,6 @@ public class DocumentUtil {\nreturn sw.toString();\n}\n- /**\n- * Marshall a DOM Element as string\n- *\n- * @param element\n- *\n- * @return\n- *\n- * @throws TransformerFactoryConfigurationError\n- * @throws TransformerException\n- */\n- public static String getDOMElementAsString(Element element) throws ProcessingException, ConfigurationException {\n- Source source = new DOMSource(element);\n- StringWriter sw = new StringWriter();\n-\n- Result streamResult = new StreamResult(sw);\n- // Write the DOM document to the file\n- Transformer xformer = TransformerUtil.getTransformer();\n- try {\n- xformer.transform(source, streamResult);\n- } catch (TransformerException e) {\n- throw logger.processingError(e);\n- }\n-\n- return sw.toString();\n- }\n-\n/**\n* <p> Get an element from the document given its {@link QName} </p> <p> First an attempt to get the element based\n* on its namespace is made, failing which an element with the localpart ignoring any namespace is returned. </p>\n@@ -348,83 +299,6 @@ public class DocumentUtil {\nreturn new ByteArrayInputStream(baos.toByteArray());\n}\n- /**\n- * Stream a DOM Node as a String\n- *\n- * @param node\n- *\n- * @return\n- *\n- * @throws ProcessingException\n- * @throws TransformerFactoryConfigurationError\n- * @throws TransformerException\n- */\n- public static String getNodeAsString(Node node) throws ConfigurationException, ProcessingException {\n- Source source = new DOMSource(node);\n- ByteArrayOutputStream baos = new ByteArrayOutputStream();\n-\n- Result streamResult = new StreamResult(baos);\n- // Write the DOM document to the stream\n- Transformer transformer = TransformerUtil.getTransformer();\n- try {\n- transformer.transform(source, streamResult);\n- } catch (TransformerException e) {\n- throw logger.processingError(e);\n- }\n-\n- return new String(baos.toByteArray(), GeneralConstants.SAML_CHARSET);\n- }\n-\n- /**\n- * Given a document, return a Node with the given node name and an attribute with a particular attribute value\n- *\n- * @param document\n- * @param nsURI\n- * @param nodeName\n- * @param attributeName\n- * @param attributeValue\n- *\n- * @return\n- *\n- * @throws XPathException\n- * @throws TransformerFactoryConfigurationError\n- * @throws TransformerException\n- */\n- public static Node getNodeWithAttribute(Document document, final String nsURI, String nodeName, String attributeName,\n- String attributeValue) throws XPathException, TransformerFactoryConfigurationError, TransformerException {\n- NodeList nl = document.getElementsByTagNameNS(nsURI, nodeName);\n- int len = nl != null ? nl.getLength() : 0;\n-\n- for (int i = 0; i < len; i++) {\n- Node n = nl.item(i);\n- if (n.getNodeType() != Node.ELEMENT_NODE)\n- continue;\n- Element el = (Element) n;\n- String attrValue = el.getAttributeNS(nsURI, attributeName);\n- if (attributeValue.equals(attrValue))\n- return el;\n- // Take care of attributes with null NS\n- attrValue = el.getAttribute(attributeName);\n- if (attributeValue.equals(attrValue))\n- return el;\n- }\n- return null;\n- }\n-\n- /**\n- * DOM3 method: Normalize the document with namespaces\n- *\n- * @param doc\n- *\n- * @return\n- */\n- public static Document normalizeNamespaces(Document doc) {\n- DOMConfiguration docConfig = doc.getDomConfig();\n- docConfig.setParameter(\"namespaces\", Boolean.TRUE);\n- doc.normalizeDocument();\n- return doc;\n- }\n-\n/**\n* Get a {@link Source} given a {@link Document}\n*\n@@ -453,37 +327,6 @@ public class DocumentUtil {\nreturn str;\n}\n- /**\n- * Log the nodes in the document\n- *\n- * @param doc\n- */\n- public static void logNodes(Document doc) {\n- visit(doc, 0);\n- }\n-\n- public static Node getNodeFromSource(Source source) throws ProcessingException, ConfigurationException {\n- try {\n- Transformer transformer = TransformerUtil.getTransformer();\n- DOMResult result = new DOMResult();\n- TransformerUtil.transform(transformer, source, result);\n- return result.getNode();\n- } catch (ParsingException te) {\n- throw logger.processingError(te);\n- }\n- }\n-\n- public static Document getDocumentFromSource(Source source) throws ProcessingException, ConfigurationException {\n- try {\n- Transformer transformer = TransformerUtil.getTransformer();\n- DOMResult result = new DOMResult();\n- TransformerUtil.transform(transformer, source, result);\n- return (Document) result.getNode();\n- } catch (ParsingException te) {\n- throw logger.processingError(te);\n- }\n- }\n-\nprivate static void visit(Node node, int level) {\n// Visit each child\nNodeList list = node.getChildNodes();\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12313 Remove unused method from org.keycloak.saml.common.util.DocumentUtil
339,686
20.12.2019 20:54:20
-3,600
1162455f3285cdb49c96836c023c2af1e7ff2167
Adds a ready indicating promise This is non-intrusive and backwards compatible. With this change it is possible to `await keycloakAuthorization.ready` to make sure the component has been properly initialized.
[ { "change_type": "MODIFY", "old_path": "adapters/oidc/js/src/main/resources/keycloak-authz.js", "new_path": "adapters/oidc/js/src/main/resources/keycloak-authz.js", "diff": "var _instance = this;\nthis.rpt = null;\n+ var resolve = function () {};\n+ var reject = function () {};\n+\n+ // detects if browser supports promises\n+ if (typeof Promise !== \"undefined\" && Promise.toString().indexOf(\"[native code]\") !== -1) {\n+ this.ready = new Promise(function (res, rej) {\n+ resolve = res;\n+ reject = rej;\n+ });\n+ }\n+\nthis.init = function () {\nvar request = new XMLHttpRequest();\nif (request.readyState == 4) {\nif (request.status == 200) {\n_instance.config = JSON.parse(request.responseText);\n+ resolve();\n} else {\nconsole.error('Could not obtain configuration from server.');\n+ reject();\n}\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-10894 Adds a ready indicating promise This is non-intrusive and backwards compatible. With this change it is possible to `await keycloakAuthorization.ready` to make sure the component has been properly initialized.
339,147
24.12.2019 23:06:55
-3,600
44ab3f46b7866005f24059546f9da0b26cba739f
Spring Boot does not honour wildcard auth-role
[ { "change_type": "MODIFY", "old_path": "adapters/oidc/spring-boot-adapter-core/src/main/java/org/keycloak/adapters/springboot/KeycloakBaseSpringBootConfiguration.java", "new_path": "adapters/oidc/spring-boot-adapter-core/src/main/java/org/keycloak/adapters/springboot/KeycloakBaseSpringBootConfiguration.java", "diff": "package org.keycloak.adapters.springboot;\nimport io.undertow.servlet.api.DeploymentInfo;\n+import io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic;\nimport io.undertow.servlet.api.WebResourceCollection;\nimport org.apache.catalina.Context;\n+import org.apache.log4j.Logger;\nimport org.apache.tomcat.util.descriptor.web.LoginConfig;\nimport org.apache.tomcat.util.descriptor.web.SecurityCollection;\nimport org.apache.tomcat.util.descriptor.web.SecurityConstraint;\n@@ -32,6 +34,7 @@ import org.eclipse.jetty.server.handler.HandlerList;\nimport org.eclipse.jetty.server.handler.HandlerWrapper;\nimport org.eclipse.jetty.util.security.Constraint;\nimport org.eclipse.jetty.webapp.WebAppContext;\n+import org.keycloak.adapters.KeycloakDeploymentBuilder;\nimport org.keycloak.adapters.jetty.KeycloakJettyAuthenticator;\nimport org.keycloak.adapters.undertow.KeycloakServletExtension;\nimport org.springframework.beans.factory.annotation.Autowired;\n@@ -39,6 +42,7 @@ import org.springframework.context.ApplicationContext;\nimport java.util.ArrayList;\nimport java.util.HashSet;\n+import java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\n@@ -76,8 +80,31 @@ public class KeycloakBaseSpringBootConfiguration {\ndeploymentInfo.setLoginConfig(loginConfig);\ndeploymentInfo.addInitParameter(\"keycloak.config.resolver\", KeycloakSpringBootConfigResolverWrapper.class.getName());\n- deploymentInfo.addSecurityConstraints(getSecurityConstraints());\n+\n+ /* Support for '*' as all roles allowed\n+ * We clear out the role in the SecurityConstraints\n+ * and set the EmptyRoleSemantic to Authenticate\n+ * But we will set EmptyRoleSemantic to DENY (default)\n+ * if roles are non existing or left empty\n+ */\n+ Iterator<io.undertow.servlet.api.SecurityConstraint> it = this.getSecurityConstraints().iterator();\n+ while (it.hasNext()) {\n+ io.undertow.servlet.api.SecurityConstraint securityConstraint = it.next();\n+ Set<String> rolesAllowed = securityConstraint.getRolesAllowed();\n+\n+ if (rolesAllowed.contains(\"*\") || rolesAllowed.contains(\"**\") ) {\n+ io.undertow.servlet.api.SecurityConstraint allRolesAllowed = new io.undertow.servlet.api.SecurityConstraint();\n+ allRolesAllowed.setEmptyRoleSemantic(EmptyRoleSemantic.AUTHENTICATE);\n+ allRolesAllowed.setTransportGuaranteeType(securityConstraint.getTransportGuaranteeType());\n+ for (WebResourceCollection wr : securityConstraint.getWebResourceCollections()) {\n+ allRolesAllowed.addWebResourceCollection(wr);\n+ }\n+ deploymentInfo.addSecurityConstraint(allRolesAllowed);\n+ } else // left empty will fall back on default EmptyRoleSemantic.DENY\n+ deploymentInfo.addSecurityConstraint(securityConstraint);\n+\n+ }\ndeploymentInfo.addServletExtension(new KeycloakServletExtension());\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[KEYCLOAK-6008] - Spring Boot does not honour wildcard auth-role (#6579)
339,465
02.01.2020 17:53:56
-3,600
fa453e9c0c798995547f886b7a61baf5ae00516f
Default first broker login flow is broken after migration
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/migration/MigrationModelManager.java", "new_path": "server-spi-private/src/main/java/org/keycloak/migration/MigrationModelManager.java", "diff": "@@ -47,6 +47,7 @@ import org.keycloak.migration.migrators.MigrateTo4_2_0;\nimport org.keycloak.migration.migrators.MigrateTo4_6_0;\nimport org.keycloak.migration.migrators.MigrateTo6_0_0;\nimport org.keycloak.migration.migrators.MigrateTo8_0_0;\n+import org.keycloak.migration.migrators.MigrateTo8_0_2;\nimport org.keycloak.migration.migrators.MigrateTo9_0_0;\nimport org.keycloak.migration.migrators.Migration;\nimport org.keycloak.models.KeycloakSession;\n@@ -86,6 +87,7 @@ public class MigrationModelManager {\nnew MigrateTo4_6_0(),\nnew MigrateTo6_0_0(),\nnew MigrateTo8_0_0(),\n+ new MigrateTo8_0_2(),\nnew MigrateTo9_0_0()\n};\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_2.java", "diff": "+/*\n+ * Copyright 2019 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+\n+package org.keycloak.migration.migrators;\n+\n+import java.util.LinkedList;\n+\n+import org.jboss.logging.Logger;\n+import org.keycloak.migration.ModelVersion;\n+import org.keycloak.models.AuthenticationExecutionModel;\n+import org.keycloak.models.AuthenticationFlowModel;\n+import org.keycloak.models.KeycloakSession;\n+import org.keycloak.models.RealmModel;\n+import org.keycloak.representations.idm.RealmRepresentation;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Marek Posolda</a>\n+ */\n+public class MigrateTo8_0_2 implements Migration {\n+\n+ public static final ModelVersion VERSION = new ModelVersion(\"8.0.2\");\n+\n+ private static final Logger LOG = Logger.getLogger(MigrateTo8_0_2.class);\n+\n+ @Override\n+ public ModelVersion getVersion() {\n+ return VERSION;\n+ }\n+\n+ @Override\n+ public void migrate(KeycloakSession session) {\n+ session.realms().getRealms().forEach(this::migrateAuthenticationFlowsWithAlternativeRequirements);\n+ }\n+\n+ @Override\n+ public void migrateImport(KeycloakSession session, RealmModel realm, RealmRepresentation rep, boolean skipUserDependent) {\n+ migrateAuthenticationFlowsWithAlternativeRequirements(realm);\n+ }\n+\n+\n+ protected void migrateAuthenticationFlowsWithAlternativeRequirements(RealmModel realm) {\n+ for (AuthenticationFlowModel flow : realm.getAuthenticationFlows()) {\n+\n+ boolean alternativeFound = false;\n+ boolean requiredFound = false;\n+ for (AuthenticationExecutionModel execution : realm.getAuthenticationExecutions(flow.getId())) {\n+ switch (execution.getRequirement()) {\n+ case REQUIRED:\n+ case CONDITIONAL:\n+ requiredFound = true;\n+ break;\n+ case ALTERNATIVE:\n+ alternativeFound = true;\n+ break;\n+ }\n+ }\n+\n+ // This flow contains some REQUIRED and ALTERNATIVE at the same level. We will migrate ALTERNATIVES to separate subflows\n+ // to try to preserve same behaviour as in previous versions\n+ if (requiredFound && alternativeFound) {\n+\n+ // Suffix used just to avoid name conflicts\n+ int suffix = 0;\n+ LinkedList<AuthenticationExecutionModel> alternativesToMigrate = new LinkedList<>();\n+ for (AuthenticationExecutionModel execution : realm.getAuthenticationExecutions(flow.getId())) {\n+ if (AuthenticationExecutionModel.Requirement.ALTERNATIVE.equals(execution.getRequirement())) {\n+ alternativesToMigrate.add(execution);\n+ }\n+\n+ // If we have some REQUIRED then ALTERNATIVE and then REQUIRED/CONDITIONAL, we migrate the alternatives to the new subflow.\n+ if (AuthenticationExecutionModel.Requirement.REQUIRED.equals(execution.getRequirement()) ||\n+ AuthenticationExecutionModel.Requirement.CONDITIONAL.equals(execution.getRequirement())) {\n+ if (!alternativesToMigrate.isEmpty()) {\n+ migrateAlternatives(realm, flow, alternativesToMigrate, suffix);\n+ suffix += 1;\n+ alternativesToMigrate.clear();\n+ }\n+ }\n+ }\n+\n+ if (!alternativesToMigrate.isEmpty()) {\n+ migrateAlternatives(realm, flow, alternativesToMigrate, suffix);\n+ }\n+ }\n+ }\n+ }\n+\n+\n+ private void migrateAlternatives(RealmModel realm, AuthenticationFlowModel parentFlow,\n+ LinkedList<AuthenticationExecutionModel> alternativesToMigrate, int suffix) {\n+ LOG.debugf(\"Migrating %d ALTERNATIVE executions in the flow '%s' of realm '%s' to separate subflow\", alternativesToMigrate.size(),\n+ parentFlow.getAlias(), realm.getName());\n+\n+ AuthenticationFlowModel newFlow = new AuthenticationFlowModel();\n+ newFlow.setTopLevel(false);\n+ newFlow.setBuiltIn(parentFlow.isBuiltIn());\n+ newFlow.setAlias(parentFlow.getAlias() + \" - Alternatives - \" + suffix);\n+ newFlow.setDescription(\"Subflow of \" + parentFlow.getAlias() + \" with alternative executions\");\n+ newFlow.setProviderId(\"basic-flow\");\n+ newFlow = realm.addAuthenticationFlow(newFlow);\n+\n+ AuthenticationExecutionModel execution = new AuthenticationExecutionModel();\n+ execution.setParentFlow(parentFlow.getId());\n+ execution.setRequirement(AuthenticationExecutionModel.Requirement.REQUIRED);\n+ execution.setFlowId(newFlow.getId());\n+ // Use same priority as the first ALTERNATIVE as new execution will defacto replace it in the parent flow\n+ execution.setPriority(alternativesToMigrate.getFirst().getPriority());\n+ execution.setAuthenticatorFlow(true);\n+ realm.addAuthenticatorExecution(execution);\n+\n+ int priority = 0;\n+ for (AuthenticationExecutionModel ex : alternativesToMigrate) {\n+ priority += 10;\n+ ex.setParentFlow(newFlow.getId());\n+ ex.setPriority(priority);\n+ realm.updateAuthenticatorExecution(ex);\n+ }\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/HOW-TO-RUN.md", "new_path": "testsuite/integration-arquillian/HOW-TO-RUN.md", "diff": "@@ -347,7 +347,7 @@ Run the test (Update according to your DB connection, versions etc):\nmvn -B -f testsuite/integration-arquillian/pom.xml \\\nclean install \\\n- -Pjpa,auth-server-wildfly,db-mysql,auth-server-migration \\\n+ -Pjpa,auth-server-wildfly,db-mariadb,auth-server-migration \\\n-Dauth.server.jboss.startup.timeout=900 \\\n-Dtest=MigrationTest \\\n-Dmigration.mode=auto \\\n@@ -355,10 +355,7 @@ Run the test (Update according to your DB connection, versions etc):\n-Dprevious.product.unpacked.folder.name=keycloak-$OLD_KEYCLOAK_VERSION \\\n-Dmigration.import.file.name=migration-realm-$OLD_KEYCLOAK_VERSION.json \\\n-Dauth.server.ssl.required=false \\\n- -Djdbc.mvn.version.legacy=5.1.38 \\\n- -Djdbc.mvn.groupId=mysql \\\n- -Djdbc.mvn.artifactId=mysql-connector-java \\\n- -Djdbc.mvn.version=8.0.12\n+ -Djdbc.mvn.version.legacy=2.2.4\nFor the available versions of old keycloak server, you can take a look to [this directory](tests/base/src/test/resources/migration-test) .\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java", "diff": "*/\npackage org.keycloak.testsuite.migration;\n-import org.apache.commons.io.IOUtils;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\n-import org.hamcrest.Matchers;\nimport org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.admin.client.resource.ClientsResource;\nimport org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.admin.client.resource.RoleResource;\n+import org.keycloak.authentication.authenticators.broker.IdpConfirmLinkAuthenticatorFactory;\n+import org.keycloak.authentication.authenticators.broker.IdpCreateUserIfUniqueAuthenticatorFactory;\n+import org.keycloak.authentication.authenticators.broker.IdpEmailVerificationAuthenticatorFactory;\n+import org.keycloak.authentication.authenticators.broker.IdpReviewProfileAuthenticatorFactory;\n+import org.keycloak.authentication.authenticators.broker.IdpUsernamePasswordFormFactory;\n+import org.keycloak.authentication.authenticators.browser.OTPFormAuthenticatorFactory;\n+import org.keycloak.authentication.authenticators.conditional.ConditionalUserConfiguredAuthenticatorFactory;\nimport org.keycloak.broker.provider.util.SimpleHttp;\nimport org.keycloak.common.constants.KerberosConstants;\nimport org.keycloak.component.PrioritizedComponentModel;\nimport org.keycloak.keys.KeyProvider;\n-import org.keycloak.models.AccountRoles;\nimport org.keycloak.models.AdminRoles;\nimport org.keycloak.models.AuthenticationExecutionModel;\n-import org.keycloak.models.ClientModel;\nimport org.keycloak.models.Constants;\nimport org.keycloak.models.LDAPConstants;\n-import org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.utils.DefaultAuthenticationFlows;\nimport org.keycloak.models.utils.TimeBasedOTP;\n@@ -64,10 +66,8 @@ import org.keycloak.testsuite.util.OAuthClient;\nimport java.io.IOException;\nimport java.net.URI;\n-import java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n-import java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\n@@ -80,7 +80,6 @@ import static org.hamcrest.Matchers.containsInAnyOrder;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.is;\n-import static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\n@@ -277,6 +276,8 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {\ntestAccountConsoleClient(masterRealm);\ntestAccountConsoleClient(migrationRealm);\ntestAlwaysDisplayInConsole();\n+ testFirstBrokerLoginFlowMigrated(masterRealm);\n+ testFirstBrokerLoginFlowMigrated(migrationRealm);\n}\nprivate void testAdminClientUrls(RealmResource realm) {\n@@ -324,6 +325,59 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {\nassertEquals(\"oidc-audience-resolve-mapper\", mappers.get(0).getProtocolMapper());\n}\n+ private void testFirstBrokerLoginFlowMigrated(RealmResource realm) {\n+ log.infof(\"Test that firstBrokerLogin flow was migrated in new realm '%s'\", realm.toRepresentation().getRealm());\n+\n+ List<AuthenticationExecutionInfoRepresentation> authExecutions = realm.flows().getExecutions(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW);\n+\n+ testAuthenticationExecution(authExecutions.get(0), null,\n+ IdpReviewProfileAuthenticatorFactory.PROVIDER_ID, AuthenticationExecutionModel.Requirement.REQUIRED, 0, 0);\n+\n+ testAuthenticationExecution(authExecutions.get(1), true,\n+ null, AuthenticationExecutionModel.Requirement.REQUIRED, 0, 1);\n+\n+ testAuthenticationExecution(authExecutions.get(2), null,\n+ IdpCreateUserIfUniqueAuthenticatorFactory.PROVIDER_ID, AuthenticationExecutionModel.Requirement.ALTERNATIVE, 1, 0);\n+\n+ testAuthenticationExecution(authExecutions.get(3), true,\n+ null, AuthenticationExecutionModel.Requirement.ALTERNATIVE, 1, 1);\n+\n+ testAuthenticationExecution(authExecutions.get(4), null,\n+ IdpConfirmLinkAuthenticatorFactory.PROVIDER_ID, AuthenticationExecutionModel.Requirement.REQUIRED, 2, 0);\n+\n+ testAuthenticationExecution(authExecutions.get(5), true,\n+ null, AuthenticationExecutionModel.Requirement.REQUIRED, 2, 1);\n+\n+ testAuthenticationExecution(authExecutions.get(6), null,\n+ IdpEmailVerificationAuthenticatorFactory.PROVIDER_ID, AuthenticationExecutionModel.Requirement.ALTERNATIVE, 3, 0);\n+\n+ testAuthenticationExecution(authExecutions.get(7), true,\n+ null, AuthenticationExecutionModel.Requirement.ALTERNATIVE, 3, 1);\n+\n+ testAuthenticationExecution(authExecutions.get(8), null,\n+ IdpUsernamePasswordFormFactory.PROVIDER_ID, AuthenticationExecutionModel.Requirement.REQUIRED, 4, 0);\n+\n+ testAuthenticationExecution(authExecutions.get(9), true,\n+ null, AuthenticationExecutionModel.Requirement.CONDITIONAL, 4, 1);\n+\n+ // There won't be a requirement in the future, so this test would need to change\n+ testAuthenticationExecution(authExecutions.get(10), null,\n+ ConditionalUserConfiguredAuthenticatorFactory.PROVIDER_ID, AuthenticationExecutionModel.Requirement.REQUIRED, 5, 0);\n+\n+ testAuthenticationExecution(authExecutions.get(11), null,\n+ OTPFormAuthenticatorFactory.PROVIDER_ID, AuthenticationExecutionModel.Requirement.REQUIRED, 5, 1);\n+ }\n+\n+\n+ private void testAuthenticationExecution(AuthenticationExecutionInfoRepresentation execution, Boolean expectedAuthenticationFlow, String expectedProviderId,\n+ AuthenticationExecutionModel.Requirement expectedRequirement, int expectedLevel, int expectedIndex) {\n+ Assert.assertEquals(execution.getAuthenticationFlow(), expectedAuthenticationFlow);\n+ Assert.assertEquals(execution.getProviderId(), expectedProviderId);\n+ Assert.assertEquals(execution.getRequirement(), expectedRequirement.toString());\n+ Assert.assertEquals(execution.getLevel(), expectedLevel);\n+ Assert.assertEquals(execution.getIndex(), expectedIndex);\n+ }\n+\nprivate void testDecisionStrategySetOnResourceServer() {\nClientsResource clients = migrationRealm.clients();\nClientRepresentation clientRepresentation = clients.findByClientId(\"authz-servlet\").get(0);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12278 Default first broker login flow is broken after migration (#6556)
339,550
03.01.2020 01:57:14
-32,400
e96725127f9bcf7d55261ab828dca11fc3a63899
Fix UserSessionProviderTest to work correctly
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java", "diff": "@@ -254,29 +254,30 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest {\n@ModelTest\npublic void testRemoveUserSessionsByUser(KeycloakSession session) {\nRealmModel realm = session.realms().getRealmByName(\"test\");\n- UserSessionModel[] sessions = createSessions(session);\n+ KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {\n+ createSessions(kcSession);\n+ });\nMap<String, Integer> clientSessionsKept = new HashMap<>();\n- for (UserSessionModel s : sessions) {\n- s = session.sessions().getUserSession(realm, s.getId());\n+ for (UserSessionModel s : session.sessions().getUserSessions(realm,\n+ session.users().getUserByUsername(\"user2\", realm))) {\n- if (!s.getUser().getUsername().equals(\"user1\")) {\nclientSessionsKept.put(s.getId(), s.getAuthenticatedClientSessions().keySet().size());\n}\n- }\n- session.sessions().removeUserSessions(realm, session.users().getUserByUsername(\"user1\", realm));\n+ KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {\n+ kcSession.sessions().removeUserSessions(realm, kcSession.users().getUserByUsername(\"user1\", realm));\n+ });\nassertTrue(session.sessions().getUserSessions(realm, session.users().getUserByUsername(\"user1\", realm)).isEmpty());\n- List<UserSessionModel> userSessions = session.sessions().getUserSessions(realm, session.users().getUserByUsername(\"user2\", realm));\n+ List<UserSessionModel> userSessions = session.sessions().getUserSessions(realm,\n+ session.users().getUserByUsername(\"user2\", realm));\n- assertSame(userSessions.size(), 0);\n-\n- session.getTransactionManager().commit();\n- // Null test removed, it seems that NULL is not a valid state under the new testsuite so we are testing for Size=0\n+ assertSame(userSessions.size(), 1);\nfor (UserSessionModel userSession : userSessions) {\n- Assert.assertEquals((int) clientSessionsKept.get(userSession.getId()), userSession.getAuthenticatedClientSessions().size());\n+ Assert.assertEquals((int) clientSessionsKept.get(userSession.getId()),\n+ userSession.getAuthenticatedClientSessions().size());\n}\n}\n@@ -295,9 +296,13 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest {\n@ModelTest\npublic void testRemoveUserSessionsByRealm(KeycloakSession session) {\nRealmModel realm = session.realms().getRealmByName(\"test\");\n- UserSessionModel[] sessions = createSessions(session);\n+ KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {\n+ createSessions(kcSession);\n+ });\n- session.sessions().removeUserSessions(realm);\n+ KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {\n+ kcSession.sessions().removeUserSessions(realm);\n+ });\nassertTrue(session.sessions().getUserSessions(realm, session.users().getUserByUsername(\"user1\", realm)).isEmpty());\nassertTrue(session.sessions().getUserSessions(realm, session.users().getUserByUsername(\"user2\", realm)).isEmpty());\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12165 Fix UserSessionProviderTest to work correctly (#6513)
339,179
06.01.2020 12:32:13
-3,600
28b01bc34d42a228229d4a56a2b2de8c5a84c3c6
Fix integer overflow for SAML XMLTimeUtil add method parameters
[ { "change_type": "MODIFY", "old_path": "saml-core/src/main/java/org/keycloak/saml/SAML2LoginResponseBuilder.java", "new_path": "saml-core/src/main/java/org/keycloak/saml/SAML2LoginResponseBuilder.java", "diff": "@@ -213,13 +213,13 @@ public class SAML2LoginResponseBuilder implements SamlProtocolExtensionsAwareBui\n//Update Conditions NotOnOrAfter\nif(assertionExpiration > 0) {\nConditionsType conditions = assertion.getConditions();\n- conditions.setNotOnOrAfter(XMLTimeUtil.add(conditions.getNotBefore(), assertionExpiration * 1000));\n+ conditions.setNotOnOrAfter(XMLTimeUtil.add(conditions.getNotBefore(), assertionExpiration * 1000L));\n}\n//Update SubjectConfirmationData NotOnOrAfter\nif(subjectExpiration > 0) {\nSubjectConfirmationDataType subjectConfirmationData = assertion.getSubject().getConfirmation().get(0).getSubjectConfirmationData();\n- subjectConfirmationData.setNotOnOrAfter(XMLTimeUtil.add(assertion.getConditions().getNotBefore(), subjectExpiration * 1000));\n+ subjectConfirmationData.setNotOnOrAfter(XMLTimeUtil.add(assertion.getConditions().getNotBefore(), subjectExpiration * 1000L));\n}\n// Create an AuthnStatementType\n@@ -232,7 +232,7 @@ public class SAML2LoginResponseBuilder implements SamlProtocolExtensionsAwareBui\nauthContextRef);\nif (sessionExpiration > 0)\n- authnStatement.setSessionNotOnOrAfter(XMLTimeUtil.add(authnStatement.getAuthnInstant(), sessionExpiration * 1000));\n+ authnStatement.setSessionNotOnOrAfter(XMLTimeUtil.add(authnStatement.getAuthnInstant(), sessionExpiration * 1000L));\nif (sessionIndex != null) authnStatement.setSessionIndex(sessionIndex);\nelse authnStatement.setSessionIndex(assertion.getID());\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java", "diff": "@@ -56,14 +56,14 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {\nassertThat(authType, notNullValue());\nassertThat(authType.getSessionNotOnOrAfter(), notNullValue());\n- assertThat(authType.getSessionNotOnOrAfter(), is(XMLTimeUtil.add(authType.getAuthnInstant(), ssoMaxLifespan * 1000)));\n+ assertThat(authType.getSessionNotOnOrAfter(), is(XMLTimeUtil.add(authType.getAuthnInstant(), ssoMaxLifespan * 1000L)));\n// Conditions\nAssert.assertNotNull(resp.getAssertions().get(0).getAssertion().getConditions());\nAssert.assertNotNull(resp.getAssertions().get(0).getAssertion().getConditions());\nConditionsType condition = resp.getAssertions().get(0).getAssertion().getConditions();\n- Assert.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessCodeLifespan * 1000), condition.getNotOnOrAfter());\n+ Assert.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessCodeLifespan * 1000L), condition.getNotOnOrAfter());\n// SubjectConfirmation (confirmationData has no NotBefore, using the previous one because it's the same)\nAssert.assertNotNull(resp.getAssertions().get(0).getAssertion().getSubject());\n@@ -77,7 +77,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {\n.orElse(null);\nAssert.assertNotNull(confirmationData);\n- Assert.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessTokenLifespan * 1000), confirmationData.getNotOnOrAfter());\n+ Assert.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessTokenLifespan * 1000L), confirmationData.getNotOnOrAfter());\nreturn null;\n}\n@@ -101,6 +101,25 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {\n}\n}\n+ @Test\n+ public void testMaxValuesForAllTimeouts() throws Exception {\n+ try(AutoCloseable c = new RealmAttributeUpdater(adminClient.realm(REALM_NAME))\n+ .updateWith(r -> {\n+ r.setSsoSessionMaxLifespan(Integer.MAX_VALUE);\n+ r.setAccessCodeLifespan(Integer.MAX_VALUE);\n+ r.setAccessTokenLifespan(Integer.MAX_VALUE);\n+ })\n+ .update()) {\n+ new SamlClientBuilder()\n+ .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), \"sales-post\").build()\n+ .login().user(bburkeUser).build()\n+ .processSamlResponse(SamlClient.Binding.POST)\n+ .transformObject(r -> checkSessionNotOnOrAfter(r, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE))\n+ .build()\n+ .execute();\n+ }\n+ }\n+\n@Test\npublic void testSamlResponseContainsSessionNotOnOrAfterAuthnLogin() throws Exception {\ntry(AutoCloseable c = new RealmAttributeUpdater(adminClient.realm(REALM_NAME))\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12609 Fix integer overflow for SAML XMLTimeUtil add method parameters
339,185
06.01.2020 13:09:26
-3,600
f7379086e06c493398cd05b097e412c53f34033b
Improve mapped byte buffer cleanup
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/vault/DefaultVaultRawSecret.java", "new_path": "services/src/main/java/org/keycloak/vault/DefaultVaultRawSecret.java", "diff": "@@ -26,6 +26,8 @@ import java.util.concurrent.ThreadLocalRandom;\n*/\npublic class DefaultVaultRawSecret implements VaultRawSecret {\n+ private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);\n+\nprivate static final VaultRawSecret EMPTY_VAULT_SECRET = new VaultRawSecret() {\n@Override\npublic Optional<ByteBuffer> get() {\n@@ -42,7 +44,7 @@ public class DefaultVaultRawSecret implements VaultRawSecret {\n}\n};\n- private final ByteBuffer rawSecret;\n+ private ByteBuffer rawSecret;\nprivate byte[] secretArray;\n@@ -80,9 +82,12 @@ public class DefaultVaultRawSecret implements VaultRawSecret {\npublic void close() {\nif (rawSecret.hasArray()) {\nThreadLocalRandom.current().nextBytes(rawSecret.array());\n- } else if (this.secretArray != null) {\n+ }\n+ if (this.secretArray != null) {\nThreadLocalRandom.current().nextBytes(this.secretArray);\n+ this.secretArray = null; // dispose of secretArray\n}\nrawSecret.clear();\n+ rawSecret = EMPTY_BUFFER;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/vault/PlainTextVaultProviderTest.java", "new_path": "services/src/test/java/org/keycloak/vault/PlainTextVaultProviderTest.java", "diff": "@@ -5,10 +5,9 @@ import org.junit.Test;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n-import java.util.ArrayList;\nimport java.util.Arrays;\n-import java.util.List;\n+import static org.hamcrest.CoreMatchers.not;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\n@@ -154,11 +153,12 @@ public class PlainTextVaultProviderTest {\n//when\nVaultRawSecret secretAfterFirstRead = provider.obtainSecret(secretName);\n+ assertThat(secretAfterFirstRead, secretContains(\"secret\"));\nsecretAfterFirstRead.close();\nVaultRawSecret secretAfterSecondRead = provider.obtainSecret(secretName);\n//then\n- assertThat(secretAfterFirstRead, secretContains(\"secret\"));\n+ assertThat(secretAfterFirstRead, not(secretContains(\"secret\")));\nassertThat(secretAfterSecondRead, secretContains(\"secret\"));\n}\n}\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12619 Improve mapped byte buffer cleanup
339,364
07.01.2020 16:51:47
-3,600
8e0e9729577fde098eb85b2180069161f8927c06
Fix compilation errors in Admin Console tests
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/realm/LoginSettingsTest.java", "new_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/realm/LoginSettingsTest.java", "diff": "@@ -41,6 +41,8 @@ import static org.junit.Assert.assertTrue;\nimport static org.keycloak.representations.idm.CredentialRepresentation.PASSWORD;\nimport static org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient;\nimport static org.keycloak.testsuite.admin.Users.setPasswordFor;\n+import static org.keycloak.testsuite.arquillian.AuthServerTestEnricher.AUTH_SERVER_PORT;\n+import static org.keycloak.testsuite.arquillian.AuthServerTestEnricher.AUTH_SERVER_SSL_REQUIRED;\nimport static org.keycloak.testsuite.auth.page.AuthRealm.TEST;\nimport static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;\nimport static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWithLoginUrlOf;\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12626 Fix compilation errors in Admin Console tests
339,152
06.01.2020 16:01:41
-3,600
f926529767b5d75819d3bc864bc4a54ed8f5879d
Vault unit test always failes on Windows
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/vault/FilesPlainTextVaultProvider.java", "new_path": "services/src/main/java/org/keycloak/vault/FilesPlainTextVaultProvider.java", "diff": "@@ -5,12 +5,9 @@ import org.jboss.logging.Logger;\nimport javax.annotation.Nonnull;\nimport java.io.IOException;\nimport java.lang.invoke.MethodHandles;\n-import java.nio.MappedByteBuffer;\n-import java.nio.channels.FileChannel;\n+import java.nio.ByteBuffer;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n-import java.nio.file.StandardOpenOption;\n-import java.util.EnumSet;\nimport java.util.List;\nimport java.util.Optional;\n@@ -58,9 +55,9 @@ public class FilesPlainTextVaultProvider extends AbstractVaultProvider {\nreturn DefaultVaultRawSecret.forBuffer(Optional.empty());\n}\n- try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(secretPath, EnumSet.of(StandardOpenOption.READ))) {\n- MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());\n- return DefaultVaultRawSecret.forBuffer(Optional.of(mappedByteBuffer));\n+ try {\n+ byte[] bytes = Files.readAllBytes(secretPath);\n+ return DefaultVaultRawSecret.forBuffer(Optional.of(ByteBuffer.wrap(bytes)));\n} catch (IOException e) {\nthrow new RuntimeException(e);\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12616 Vault unit test always failes on Windows
339,235
06.01.2020 10:36:55
-3,600
80187b54ffef0295a68a9e8b9e5b00cf1c9cb092
Add quotes in kcreg.bat to allow installation dir with spaces
[ { "change_type": "MODIFY", "old_path": "integration/client-cli/client-registration-cli/src/main/bin/kcreg.bat", "new_path": "integration/client-cli/client-registration-cli/src/main/bin/kcreg.bat", "diff": "@@ -5,4 +5,4 @@ if \"%OS%\" == \"Windows_NT\" (\n) else (\nset DIRNAME=.\\\n)\n-java %KC_OPTS% -cp %DIRNAME%\\client\\keycloak-client-registration-cli-${project.version}.jar org.keycloak.client.registration.cli.KcRegMain %*\n+java %KC_OPTS% -cp \"%DIRNAME%\\client\\keycloak-client-registration-cli-${project.version}.jar\" org.keycloak.client.registration.cli.KcRegMain %*\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-10974 Add quotes in kcreg.bat to allow installation dir with spaces
339,684
06.01.2020 14:57:12
-3,600
0f8d988d58bb3c4a444beff5d1b9b733ee9c8efb
JWKS parsing: fallback to RS256 for RSA keys without alg field
[ { "change_type": "MODIFY", "old_path": "core/src/main/java/org/keycloak/util/JWKSUtils.java", "new_path": "core/src/main/java/org/keycloak/util/JWKSUtils.java", "diff": "@@ -52,7 +52,13 @@ public class JWKSUtils {\nif (jwk.getPublicKeyUse().equals(requestedUse.asString()) && parser.isKeyTypeSupported(jwk.getKeyType())) {\nKeyWrapper keyWrapper = new KeyWrapper();\nkeyWrapper.setKid(jwk.getKeyId());\n+ if (jwk.getAlgorithm() != null) {\nkeyWrapper.setAlgorithm(jwk.getAlgorithm());\n+ }\n+ else if (jwk.getKeyType().equalsIgnoreCase(\"RSA\")){\n+ //backwards compatibility: RSA keys without \"alg\" field set are considered RS256\n+ keyWrapper.setAlgorithm(\"RS256\");\n+ }\nkeyWrapper.setType(jwk.getKeyType());\nkeyWrapper.setUse(getKeyUse(jwk.getPublicKeyUse()));\nkeyWrapper.setPublicKey(parser.toPublicKey());\n" }, { "change_type": "ADD", "old_path": null, "new_path": "core/src/test/java/org/keycloak/util/JWKSUtilsTest.java", "diff": "+/*\n+ * Copyright 2016 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.util;\n+\n+import org.junit.Test;\n+import org.keycloak.common.util.Base64Url;\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.crypto.JavaAlgorithm;\n+import org.keycloak.crypto.KeyUse;\n+import org.keycloak.crypto.KeyWrapper;\n+import org.keycloak.jose.jwk.*;\n+\n+import java.nio.charset.StandardCharsets;\n+import java.security.*;\n+import java.security.cert.X509Certificate;\n+import java.security.spec.ECGenParameterSpec;\n+import java.util.Map;\n+\n+import static org.junit.Assert.*;\n+\n+\n+public class JWKSUtilsTest {\n+\n+ @Test\n+ public void publicRs256() throws Exception {\n+ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());\n+\n+ String kidRsa1 = \"key1\";\n+ String kidRsa2 = \"key2\";\n+ String kidEC1 = \"key3\";\n+ String kidEC2 = \"key4\";\n+ String jwksJson = \"{\" +\n+ \"\\\"keys\\\": [\" +\n+ \" {\" +\n+ \" \\\"kty\\\": \\\"RSA\\\",\" +\n+ \" \\\"alg\\\": \\\"RS256\\\",\" +\n+ \" \\\"use\\\": \\\"sig\\\",\" +\n+ \" \\\"kid\\\": \\\"\" + kidRsa1 + \"\\\",\" +\n+ \" \\\"n\\\": \\\"soFDjoZ5mQ8XAA7reQAFg90inKAHk0DXMTizo4JuOsgzUbhcplIeZ7ks83hsEjm8mP8lUVaHMPMAHEIp3gu6Xxsg-s73ofx1dtt_Fo7aj8j383MFQGl8-FvixTVobNeGeC0XBBQjN8lEl-lIwOa4ZoERNAShplTej0ntDp7TQm0=\\\",\" +\n+ \" \\\"e\\\": \\\"AQAB\\\"\" +\n+ \" }\" +\n+ \" ,{\" +\n+ \" \\\"kty\\\": \\\"RSA\\\",\" +\n+ \" \\\"use\\\": \\\"sig\\\",\" +\n+ \" \\\"kid\\\": \\\"\" + kidRsa2 + \"\\\",\" +\n+ \" \\\"n\\\": \\\"soFDjoZ5mQ8XAA7reQAFg90inKAHk0DXMTizo4JuOsgzUbhcplIeZ7ks83hsEjm8mP8lUVaHMPMAHEIp3gu6Xxsg-s73ofx1dtt_Fo7aj8j383MFQGl8-FvixTVobNeGeC0XBBQjN8lEl-lIwOa4ZoERNAShplTej0ntDp7TQm0=\\\",\" +\n+ \" \\\"e\\\": \\\"AQAB\\\"\" +\n+ \" },\" +\n+ \" {\" +\n+ \" \\\"kty\\\": \\\"EC\\\",\" +\n+ \" \\\"use\\\": \\\"sig\\\",\" +\n+ \" \\\"crv\\\": \\\"P-384\\\",\" +\n+ \" \\\"kid\\\": \\\"\" + kidEC1 + \"\\\",\" +\n+ \" \\\"x\\\": \\\"KVZ5h_W0-8fXmUrxmyRpO_9vwwI7urXfyxGdxm1hpEuhPj2hhDxivnb2BhNvtC6O\\\",\" +\n+ \" \\\"y\\\": \\\"1J3JVw_zR3uB3biAE7fs3V_4tJy2M1JinzWj9a4je5GSoW6zgGV4bk85OcuyUAhj\\\",\" +\n+ \" \\\"alg\\\": \\\"ES384\\\"\" +\n+ \" },\" +\n+ \" {\" +\n+ \" \\\"kty\\\": \\\"EC\\\",\" +\n+ \" \\\"use\\\": \\\"sig\\\",\" +\n+ \" \\\"crv\\\": \\\"P-384\\\",\" +\n+ \" \\\"kid\\\": \\\"\" + kidEC2 + \"\\\",\" +\n+ \" \\\"x\\\": \\\"KVZ5h_W0-8fXmUrxmyRpO_9vwwI7urXfyxGdxm1hpEuhPj2hhDxivnb2BhNvtC6O\\\",\" +\n+ \" \\\"y\\\": \\\"1J3JVw_zR3uB3biAE7fs3V_4tJy2M1JinzWj9a4je5GSoW6zgGV4bk85OcuyUAhj\\\"\" +\n+ \" }\" +\n+ \"] }\";\n+ JSONWebKeySet jsonWebKeySet = JsonSerialization.readValue(jwksJson, JSONWebKeySet.class);\n+ Map<String, KeyWrapper> keyWrappersForUse = JWKSUtils.getKeyWrappersForUse(jsonWebKeySet, JWK.Use.SIG);\n+ assertEquals(4, keyWrappersForUse.size());\n+\n+ KeyWrapper key = keyWrappersForUse.get(kidRsa1);\n+ assertNotNull(key);\n+ assertEquals(\"RS256\", key.getAlgorithm());\n+ assertEquals(KeyUse.SIG, key.getUse());\n+ assertEquals(kidRsa1, key.getKid());\n+ assertEquals(\"RSA\", key.getType());\n+\n+ key = keyWrappersForUse.get(kidRsa2);\n+ assertNotNull(key);\n+ assertEquals(\"RS256\", key.getAlgorithm());\n+ assertEquals(KeyUse.SIG, key.getUse());\n+ assertEquals(kidRsa2, key.getKid());\n+ assertEquals(\"RSA\", key.getType());\n+\n+ key = keyWrappersForUse.get(kidEC1);\n+ assertNotNull(key);\n+ assertEquals(\"ES384\", key.getAlgorithm());\n+ assertEquals(KeyUse.SIG, key.getUse());\n+ assertEquals(kidEC1, key.getKid());\n+ assertEquals(\"EC\", key.getType());\n+\n+ key = keyWrappersForUse.get(kidEC2);\n+ assertNotNull(key);\n+ assertNull(key.getAlgorithm());\n+ assertEquals(KeyUse.SIG, key.getUse());\n+ assertEquals(kidEC2, key.getKid());\n+ assertEquals(\"EC\", key.getType());\n+ }\n+\n+\n+}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[KEYCLOAK-12299] JWKS parsing: fallback to RS256 for RSA keys without alg field
339,465
02.01.2020 17:59:24
-3,600
fea7b4e0314264b6e973d0179e2e5fe1153ff105
SPNEGO / Kerberos sends multiple 401 responses with WWW-Authenticate: Negotiate header when kerberos token is invalid
[ { "change_type": "MODIFY", "old_path": "federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java", "new_path": "federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java", "diff": "@@ -208,9 +208,14 @@ public class KerberosFederationProvider implements UserStorageProvider,\nreturn new CredentialValidationOutput(user, CredentialValidationOutput.Status.AUTHENTICATED, state);\n}\n- } else {\n+ } else if (spnegoAuthenticator.getResponseToken() != null) {\n+ // Case when SPNEGO handshake requires multiple steps\n+ logger.tracef(\"SPNEGO Handshake will continue\");\nstate.put(KerberosConstants.RESPONSE_TOKEN, spnegoAuthenticator.getResponseToken());\nreturn new CredentialValidationOutput(null, CredentialValidationOutput.Status.CONTINUE, state);\n+ } else {\n+ logger.tracef(\"SPNEGO Handshake not successful\");\n+ return CredentialValidationOutput.failed();\n}\n} else {\n" }, { "change_type": "MODIFY", "old_path": "federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java", "new_path": "federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java", "diff": "@@ -712,9 +712,14 @@ public class LDAPStorageProvider implements UserStorageProvider,\nreturn new CredentialValidationOutput(user, CredentialValidationOutput.Status.AUTHENTICATED, state);\n}\n- } else {\n+ } else if (spnegoAuthenticator.getResponseToken() != null) {\n+ // Case when SPNEGO handshake requires multiple steps\n+ logger.tracef(\"SPNEGO Handshake will continue\");\nstate.put(KerberosConstants.RESPONSE_TOKEN, spnegoAuthenticator.getResponseToken());\nreturn new CredentialValidationOutput(null, CredentialValidationOutput.Status.CONTINUE, state);\n+ } else {\n+ logger.tracef(\"SPNEGO Handshake not successful\");\n+ return CredentialValidationOutput.failed();\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosSingleRealmTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosSingleRealmTest.java", "diff": "package org.keycloak.testsuite.federation.kerberos;\n+import java.net.URI;\nimport java.util.List;\n+import java.util.concurrent.atomic.AtomicReference;\n+import javax.ws.rs.client.Entity;\nimport javax.ws.rs.core.HttpHeaders;\n+import javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.core.Response;\nimport org.ietf.jgss.GSSCredential;\n@@ -37,6 +41,7 @@ import org.keycloak.representations.AccessToken;\nimport org.keycloak.representations.idm.ProtocolMapperRepresentation;\nimport org.keycloak.representations.idm.UserRepresentation;\nimport org.keycloak.storage.UserStorageProvider;\n+import org.keycloak.testsuite.ActionURIUtils;\nimport org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.admin.ApiUtil;\n@@ -62,6 +67,43 @@ public abstract class AbstractKerberosSingleRealmTest extends AbstractKerberosTe\nresponse.close();\n}\n+\n+ // KEYCLOAK-12424\n+ @Test\n+ public void spnegoWithInvalidTokenTest() throws Exception {\n+ initHttpClient(true);\n+\n+ // Update kerberos configuration with some invalid location of keytab file\n+ AtomicReference<String> origKeytab = new AtomicReference<>();\n+ updateUserStorageProvider(kerberosProviderRep -> {\n+ String keytab = kerberosProviderRep.getConfig().getFirst(KerberosConstants.KEYTAB);\n+ origKeytab.set(keytab);\n+\n+ kerberosProviderRep.getConfig().putSingle(KerberosConstants.KEYTAB, keytab + \"-invalid\");\n+ });\n+\n+ try {\n+ /*\n+ To do this we do a valid kerberos login on client side. The authenticator will obtain a valid token, but user\n+ storage provider is incorrectly configured, so SPNEGO login will fail on server side. However the server should continue to\n+ the login page (username/password) and return status 200. It should not return 401 with \"Kerberos unsupported\" page as that\n+ would display some strange dialogs in the web browser on windows - see KEYCLOAK-12424\n+ */\n+ Response spnegoResponse = spnegoLogin(\"hnelson\", \"secret\");\n+\n+ Assert.assertEquals(200, spnegoResponse.getStatus());\n+ String context = spnegoResponse.readEntity(String.class);\n+ spnegoResponse.close();\n+\n+ org.junit.Assert.assertTrue(context.contains(\"Log in to test\"));\n+\n+ events.clear();\n+ } finally {\n+ // Revert keytab configuration\n+ updateUserStorageProvider(kerberosProviderRep -> kerberosProviderRep.getConfig().putSingle(KerberosConstants.KEYTAB, origKeytab.get()));\n+ }\n+ }\n+\n// KEYCLOAK-7823\n@Test\npublic void spnegoLoginWithRequiredKerberosAuthExecutionTest() {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java", "diff": "@@ -25,6 +25,7 @@ import java.util.Hashtable;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n+import java.util.function.Consumer;\nimport javax.naming.Context;\nimport javax.naming.NamingException;\n@@ -337,18 +338,25 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {\nprotected void updateProviderEditMode(UserStorageProvider.EditMode editMode) {\n- List<ComponentRepresentation> reps = testRealmResource().components().query(\"test\", UserStorageProvider.class.getName());\n- Assert.assertEquals(1, reps.size());\n- ComponentRepresentation kerberosProvider = reps.get(0);\n- kerberosProvider.getConfig().putSingle(LDAPConstants.EDIT_MODE, editMode.toString());\n- testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider);\n+ updateUserStorageProvider(kerberosProvider -> kerberosProvider.getConfig().putSingle(LDAPConstants.EDIT_MODE, editMode.toString()));\n}\nprotected void updateProviderValidatePasswordPolicy(Boolean validatePasswordPolicy) {\n+ updateUserStorageProvider(kerberosProvider -> kerberosProvider.getConfig().putSingle(LDAPConstants.VALIDATE_PASSWORD_POLICY, validatePasswordPolicy.toString()));\n+ }\n+\n+\n+ /**\n+ * Update UserStorage provider (Kerberos provider or LDAP provider with Kerberos enabled) with specified updater and save it\n+ *\n+ */\n+ protected void updateUserStorageProvider(Consumer<ComponentRepresentation> updater) {\nList<ComponentRepresentation> reps = testRealmResource().components().query(\"test\", UserStorageProvider.class.getName());\nAssert.assertEquals(1, reps.size());\nComponentRepresentation kerberosProvider = reps.get(0);\n- kerberosProvider.getConfig().putSingle(LDAPConstants.VALIDATE_PASSWORD_POLICY, validatePasswordPolicy.toString());\n+\n+ updater.accept(kerberosProvider);\n+\ntestRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider);\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12424 SPNEGO / Kerberos sends multiple 401 responses with WWW-Authenticate: Negotiate header when kerberos token is invalid
339,528
31.12.2019 10:57:37
21,600
5082ed2fcba935d7b409e1732f400c5ddc52daae
[ ] Passing email in login_hint query parameter during Identity brokering fails when an account already exists
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/broker/IdpUsernamePasswordForm.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/broker/IdpUsernamePasswordForm.java", "diff": "@@ -63,7 +63,7 @@ public class IdpUsernamePasswordForm extends UsernamePasswordForm {\nthrow new AuthenticationFlowException(\"Not found serialized context in clientSession\", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);\n}\n- formData.add(AuthenticationManager.FORM_USERNAME, existingUser.getUsername());\n+ formData.putSingle(AuthenticationManager.FORM_USERNAME, existingUser.getUsername());\nreturn context.form()\n.setFormData(formData)\n.setAttribute(LoginFormsProvider.USERNAME_EDIT_DISABLED, true)\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[ KEYCLOAK-12606 ] Passing email in login_hint query parameter during Identity brokering fails when an account already exists
339,500
10.01.2020 10:35:09
-3,600
39fff1c538034f58548de9212160fa4ca2491b22
Cannot instantiate WebAuthnCredentialProviderFactory with Jackson 2.10.0
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<hibernate.core.version>5.3.13.Final</hibernate.core.version>\n<hibernate.c3p0.version>5.3.13.Final</hibernate.c3p0.version>\n<infinispan.version>9.4.16.Final</infinispan.version>\n+ <!-- Will be used in the product. Upstream versions are overridden in the community profile -->\n<jackson.version>2.9.10</jackson.version>\n<jackson.databind.version>2.9.10.1</jackson.databind.version>\n<jakarta.mail.version>1.6.4</jakarta.mail.version>\n<product.name-html>\\u003Cdiv class=\"kc-logo-text\"\\u003E\\u003Cspan\\u003EKeycloak\\u003C\\u002Fspan\\u003E\\u003C\\u002Fdiv\\u003E</product.name-html>\n<product.version>${project.version}</product.version>\n<product.default-profile>community</product.default-profile>\n+ <jackson.version>2.9.10</jackson.version>\n+ <jackson.databind.version>2.9.10.1</jackson.databind.version>\n</properties>\n</profile>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12513 Cannot instantiate WebAuthnCredentialProviderFactory with Jackson 2.10.0
339,281
13.01.2020 13:58:20
-3,600
3b1bdb216adb14dff916693e26a935b3320900cd
Add support for system property or env variable in AllowedClockSkew in keycloak-saml subsystem
[ { "change_type": "MODIFY", "old_path": "adapters/saml/as7-eap6/subsystem/src/main/java/org/keycloak/subsystem/saml/as7/AllowedClockSkew.java", "new_path": "adapters/saml/as7-eap6/subsystem/src/main/java/org/keycloak/subsystem/saml/as7/AllowedClockSkew.java", "diff": "@@ -32,8 +32,8 @@ abstract public class AllowedClockSkew {\nstatic final SimpleAttributeDefinition ALLOWED_CLOCK_SKEW_VALUE =\nnew SimpleAttributeDefinitionBuilder(Constants.Model.ALLOWED_CLOCK_SKEW_VALUE, ModelType.INT, false)\n.setXmlName(Constants.XML.ALLOWED_CLOCK_SKEW)\n- .setAllowExpression(false)\n- .setValidator(new IntRangeValidator(1, Integer.MAX_VALUE, true, false))\n+ .setAllowExpression(true)\n+ .setValidator(new IntRangeValidator(1, Integer.MAX_VALUE, true, true))\n.build();\nstatic private enum AllowedClockSkewUnits {MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS};\n@@ -41,9 +41,9 @@ abstract public class AllowedClockSkew {\nstatic final SimpleAttributeDefinition ALLOWED_CLOCK_SKEW_UNIT =\nnew SimpleAttributeDefinitionBuilder(Constants.Model.ALLOWED_CLOCK_SKEW_UNIT, ModelType.STRING, true)\n.setXmlName(Constants.XML.ALLOWED_CLOCK_SKEW_UNIT)\n- .setAllowExpression(false)\n+ .setAllowExpression(true)\n.setDefaultValue(new ModelNode(AllowedClockSkewUnits.SECONDS.name()))\n- .setValidator(EnumValidator.create(AllowedClockSkewUnits.class, true, false))\n+ .setValidator(EnumValidator.create(AllowedClockSkewUnits.class, true, true))\n.build();\nstatic final SimpleAttributeDefinition[] ATTRIBUTES = {ALLOWED_CLOCK_SKEW_UNIT, ALLOWED_CLOCK_SKEW_VALUE};\n" }, { "change_type": "MODIFY", "old_path": "adapters/saml/as7-eap6/subsystem/src/test/java/org/keycloak/subsystem/saml/as7/SubsystemParsingAllowedClockSkewTestCase.java", "new_path": "adapters/saml/as7-eap6/subsystem/src/test/java/org/keycloak/subsystem/saml/as7/SubsystemParsingAllowedClockSkewTestCase.java", "diff": "@@ -184,16 +184,15 @@ public class SubsystemParsingAllowedClockSkewTestCase extends AbstractSubsystemB\ntestSubsystem(\"30\", \"invalid-unit\");\n}\n- // For the moment no expressions allowed as the rest of the subsystem doesn't resolve expressions\n- //@Test\n- //public void testExpression() throws Exception {\n- // System.setProperty(\"test.prop.SKEW_TIME\", \"30\");\n- // System.setProperty(\"test.prop.SKEW_UNIT\", \"MILLISECONDS\");\n- // try {\n- // testSubsystem(\"${test.prop.SKEW_TIME}\", \"${test.prop.SKEW_UNIT}\", 30, \"MILLISECONDS\");\n- // } finally {\n- // System.clearProperty(\"test.prop.SKEW_TIME\");\n- // System.clearProperty(\"test.prop.SKEW_UNIT\");\n- // }\n- //}\n+ @Test\n+ public void testExpression() throws Exception {\n+ System.setProperty(\"test.prop.SKEW_TIME\", \"30\");\n+ System.setProperty(\"test.prop.SKEW_UNIT\", \"MILLISECONDS\");\n+ try {\n+ testSubsystem(\"${test.prop.SKEW_TIME}\", \"${test.prop.SKEW_UNIT}\", 30, \"MILLISECONDS\");\n+ } finally {\n+ System.clearProperty(\"test.prop.SKEW_TIME\");\n+ System.clearProperty(\"test.prop.SKEW_UNIT\");\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/IdpParser.java", "new_path": "adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/IdpParser.java", "diff": "@@ -78,7 +78,7 @@ public class IdpParser extends AbstractKeycloakSamlAdapterV1Parser<IDP> {\nString timeUnitString = StaxParserUtil.getAttributeValueRP(elementDetail, KeycloakSamlAdapterV1QNames.ATTR_UNIT);\ntarget.setAllowedClockSkewUnit(timeUnitString == null ? TimeUnit.SECONDS : TimeUnit.valueOf(timeUnitString));\nStaxParserUtil.advance(xmlEventReader);\n- target.setAllowedClockSkew(Integer.parseInt(StaxParserUtil.getElementText(xmlEventReader)));\n+ target.setAllowedClockSkew(Integer.parseInt(StaxParserUtil.getElementTextRP(xmlEventReader)));\nbreak;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "adapters/saml/wildfly/wildfly-subsystem/src/main/java/org/keycloak/subsystem/adapter/saml/extension/AllowedClockSkew.java", "new_path": "adapters/saml/wildfly/wildfly-subsystem/src/main/java/org/keycloak/subsystem/adapter/saml/extension/AllowedClockSkew.java", "diff": "*/\npackage org.keycloak.subsystem.adapter.saml.extension;\n+import java.util.EnumSet;\nimport org.jboss.as.controller.SimpleAttributeDefinition;\nimport org.jboss.as.controller.SimpleAttributeDefinitionBuilder;\nimport org.jboss.as.controller.operations.validation.EnumValidator;\n@@ -32,8 +33,8 @@ abstract public class AllowedClockSkew {\nstatic final SimpleAttributeDefinition ALLOWED_CLOCK_SKEW_VALUE =\nnew SimpleAttributeDefinitionBuilder(Constants.Model.ALLOWED_CLOCK_SKEW_VALUE, ModelType.INT, false)\n.setXmlName(Constants.XML.ALLOWED_CLOCK_SKEW)\n- .setAllowExpression(false)\n- .setValidator(new IntRangeValidator(1, Integer.MAX_VALUE, true, false))\n+ .setAllowExpression(true)\n+ .setValidator(new IntRangeValidator(1, Integer.MAX_VALUE, true, true))\n.build();\nstatic private enum AllowedClockSkewUnits {MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS};\n@@ -41,12 +42,12 @@ abstract public class AllowedClockSkew {\nstatic final SimpleAttributeDefinition ALLOWED_CLOCK_SKEW_UNIT =\nnew SimpleAttributeDefinitionBuilder(Constants.Model.ALLOWED_CLOCK_SKEW_UNIT, ModelType.STRING, true)\n.setXmlName(Constants.XML.ALLOWED_CLOCK_SKEW_UNIT)\n- .setAllowExpression(false)\n+ .setAllowExpression(true)\n.setDefaultValue(new ModelNode(AllowedClockSkewUnits.SECONDS.name()))\n.setAllowedValues(AllowedClockSkewUnits.MINUTES.name(), AllowedClockSkewUnits.SECONDS.name(),\nAllowedClockSkewUnits.MILLISECONDS.name(), AllowedClockSkewUnits.MICROSECONDS.name(),\nAllowedClockSkewUnits.NANOSECONDS.name())\n- .setValidator(EnumValidator.create(AllowedClockSkewUnits.class, true, false))\n+ .setValidator(EnumValidator.create(AllowedClockSkewUnits.class, EnumSet.allOf(AllowedClockSkewUnits.class)))\n.build();\nstatic final SimpleAttributeDefinition[] ATTRIBUTES = {ALLOWED_CLOCK_SKEW_UNIT, ALLOWED_CLOCK_SKEW_VALUE};\n" }, { "change_type": "MODIFY", "old_path": "adapters/saml/wildfly/wildfly-subsystem/src/test/java/org/keycloak/subsystem/adapter/saml/extension/SubsystemParsingAllowedClockSkewTestCase.java", "new_path": "adapters/saml/wildfly/wildfly-subsystem/src/test/java/org/keycloak/subsystem/adapter/saml/extension/SubsystemParsingAllowedClockSkewTestCase.java", "diff": "@@ -223,16 +223,15 @@ public class SubsystemParsingAllowedClockSkewTestCase extends AbstractSubsystemB\ntestSubsystem(\"30\", \"invalid-unit\");\n}\n- // For the moment no expressions allowed as the rest of the subsystem doesn't resolve expressions\n- //@Test\n- //public void testExpression() throws Exception {\n- // System.setProperty(\"test.prop.SKEW_TIME\", \"30\");\n- // System.setProperty(\"test.prop.SKEW_UNIT\", \"MILLISECONDS\");\n- // try {\n- // testSubsystem(\"${test.prop.SKEW_TIME}\", \"${test.prop.SKEW_UNIT}\", 30, \"MILLISECONDS\");\n- // } finally {\n- // System.clearProperty(\"test.prop.SKEW_TIME\");\n- // System.clearProperty(\"test.prop.SKEW_UNIT\");\n- // }\n- //}\n+ @Test\n+ public void testExpression() throws Exception {\n+ System.setProperty(\"test.prop.SKEW_TIME\", \"30\");\n+ System.setProperty(\"test.prop.SKEW_UNIT\", \"MILLISECONDS\");\n+ try {\n+ testSubsystem(\"${test.prop.SKEW_TIME}\", \"${test.prop.SKEW_UNIT}\", 30, \"MILLISECONDS\");\n+ } finally {\n+ System.clearProperty(\"test.prop.SKEW_TIME\");\n+ System.clearProperty(\"test.prop.SKEW_UNIT\");\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "saml-core/src/main/java/org/keycloak/saml/common/util/StaxParserUtil.java", "new_path": "saml-core/src/main/java/org/keycloak/saml/common/util/StaxParserUtil.java", "diff": "@@ -494,6 +494,24 @@ public class StaxParserUtil {\nreturn str;\n}\n+ /**\n+ * Get the element text, replacing every occurrence of ${..} by corresponding system property value\n+ *\n+ * @param xmlEventReader\n+ *\n+ * @return A <b>trimmed</b> string value with all property references replaced if any.\n+ * If there are no valid references the input string will be returned\n+ *\n+ * @throws ParsingException\n+ */\n+ public static String getElementTextRP(XMLEventReader xmlEventReader) throws ParsingException {\n+ try {\n+ return trim(StringPropertyReplacer.replaceProperties(xmlEventReader.getElementText()));\n+ } catch (XMLStreamException e) {\n+ throw logger.parserException(e);\n+ }\n+ }\n+\n/**\n* Get the XML event reader\n*\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java", "diff": "@@ -134,7 +134,7 @@ public abstract class AbstractServletsAdapterTest extends AbstractAdapterTest {\nif (clockSkewSec != null) {\nString keycloakSamlXMLContent = IOUtils.toString(keycloakSAMLConfig.openStream(), Charset.forName(\"UTF-8\"))\n- .replace(\"%CLOCK_SKEW%\", String.valueOf(clockSkewSec));\n+ .replace(\"%CLOCK_SKEW%\", \"${allowed.clock.skew:\" + String.valueOf(clockSkewSec) + \"}\");\ndeployment.addAsWebInfResource(new StringAsset(keycloakSamlXMLContent), \"keycloak-saml.xml\");\n} else {\ndeployment.addAsWebInfResource(keycloakSAMLConfig, \"keycloak-saml.xml\");\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-11486 Add support for system property or env variable in AllowedClockSkew in keycloak-saml subsystem
339,713
09.01.2020 13:45:21
10,800
4cbe478129fdddd5dadd1b58e110ce683abc9feb
Fix use bytesRead to make sure the output stream does not get padded with null bytes.
[ { "change_type": "MODIFY", "old_path": "adapters/spi/servlet-adapter-spi/src/main/java/org/keycloak/adapters/servlet/FilterSessionStore.java", "new_path": "adapters/spi/servlet-adapter-spi/src/main/java/org/keycloak/adapters/servlet/FilterSessionStore.java", "diff": "@@ -396,7 +396,7 @@ public class FilterSessionStore implements AdapterSessionStore {\nInputStream is = request.getInputStream();\nwhile ( (bytesRead = is.read(buffer) ) >= 0) {\n- os.write(buffer);\n+ os.write(buffer, 0, bytesRead);\ntotalRead += bytesRead;\nif (totalRead > maxBuffer) {\nthrow new RuntimeException(\"max buffer reached on a saved request\");\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Fix KEYCLOAK-10838, use bytesRead to make sure the output stream does not get padded with null bytes.
339,317
30.11.2019 01:30:53
-10,800
b6a3fba6e30fdac0466c4280e85857c5e1271dac
Remove unused method from org.keycloak.saml.processing.core.saml.v2.factories.JBossSAMLAuthnResponseFactory
[ { "change_type": "MODIFY", "old_path": "saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/factories/JBossSAMLAuthnResponseFactory.java", "new_path": "saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/factories/JBossSAMLAuthnResponseFactory.java", "diff": "package org.keycloak.saml.processing.core.saml.v2.factories;\nimport org.keycloak.dom.saml.v2.assertion.AssertionType;\n-import org.keycloak.dom.saml.v2.assertion.ConditionsType;\nimport org.keycloak.dom.saml.v2.assertion.EncryptedAssertionType;\nimport org.keycloak.dom.saml.v2.assertion.NameIDType;\n-import org.keycloak.dom.saml.v2.assertion.StatementAbstractType;\n-import org.keycloak.dom.saml.v2.assertion.SubjectConfirmationDataType;\n-import org.keycloak.dom.saml.v2.assertion.SubjectConfirmationType;\n-import org.keycloak.dom.saml.v2.assertion.SubjectType;\nimport org.keycloak.dom.saml.v2.protocol.ResponseType;\nimport org.keycloak.dom.saml.v2.protocol.ResponseType.RTChoiceType;\nimport org.keycloak.dom.saml.v2.protocol.StatusCodeType;\n@@ -32,16 +27,12 @@ import org.keycloak.saml.common.PicketLinkLogger;\nimport org.keycloak.saml.common.PicketLinkLoggerFactory;\nimport org.keycloak.saml.common.constants.JBossSAMLURIConstants;\nimport org.keycloak.saml.common.exceptions.ConfigurationException;\n-import org.keycloak.saml.processing.core.saml.v2.common.IDGenerator;\n-import org.keycloak.saml.processing.core.saml.v2.holders.IDPInfoHolder;\nimport org.keycloak.saml.processing.core.saml.v2.holders.IssuerInfoHolder;\n-import org.keycloak.saml.processing.core.saml.v2.holders.SPInfoHolder;\nimport org.keycloak.saml.processing.core.saml.v2.util.XMLTimeUtil;\nimport org.w3c.dom.Element;\nimport javax.xml.datatype.XMLGregorianCalendar;\nimport java.net.URI;\n-import java.util.List;\n/**\n* Factory for the SAML v2 Authn Response\n@@ -95,64 +86,6 @@ public class JBossSAMLAuthnResponseFactory {\nreturn statusType;\n}\n- /**\n- * Create a ResponseType\n- *\n- * @param ID id of the response\n- * @param sp holder with the information about the Service Provider\n- * @param idp holder with the information on the Identity Provider\n- * @param issuerInfo holder with information on the issuer\n- *\n- * @return\n- *\n- * @throws ConfigurationException\n- */\n- public static ResponseType createResponseType(String ID, SPInfoHolder sp, IDPInfoHolder idp, IssuerInfoHolder issuerInfo)\n- throws ConfigurationException {\n- String responseDestinationURI = sp.getResponseDestinationURI();\n-\n- XMLGregorianCalendar issueInstant = XMLTimeUtil.getIssueInstant();\n-\n- // Create an assertion\n- String id = IDGenerator.create(\"ID_\");\n-\n- // Create assertion -> subject\n- SubjectType subjectType = new SubjectType();\n-\n- // subject -> nameid\n- NameIDType nameIDType = new NameIDType();\n- nameIDType.setFormat(URI.create(idp.getNameIDFormat()));\n- nameIDType.setValue(idp.getNameIDFormatValue());\n-\n- SubjectType.STSubType subType = new SubjectType.STSubType();\n- subType.addBaseID(nameIDType);\n- subjectType.setSubType(subType);\n-\n- SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType();\n- subjectConfirmation.setMethod(idp.getSubjectConfirmationMethod());\n-\n- SubjectConfirmationDataType subjectConfirmationData = new SubjectConfirmationDataType();\n- subjectConfirmationData.setInResponseTo(sp.getRequestID());\n- subjectConfirmationData.setRecipient(responseDestinationURI);\n- //subjectConfirmationData.setNotBefore(issueInstant);\n- subjectConfirmationData.setNotOnOrAfter(issueInstant);\n-\n- subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);\n-\n- subjectType.addConfirmation(subjectConfirmation);\n-\n- AssertionType assertionType = SAMLAssertionFactory.createAssertion(id, nameIDType, issueInstant, (ConditionsType) null,\n- subjectType, (List<StatementAbstractType>) null);\n-\n- ResponseType responseType = createResponseType(ID, issuerInfo, assertionType);\n- // InResponseTo ID\n- responseType.setInResponseTo(sp.getRequestID());\n- // Destination\n- responseType.setDestination(responseDestinationURI);\n-\n- return responseType;\n- }\n-\n/**\n* Create a Response Type\n*\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12568 Remove unused method from org.keycloak.saml.processing.core.saml.v2.factories.JBossSAMLAuthnResponseFactory
339,192
14.01.2020 18:23:13
-32,400
221aad98770647ee8059b000ec4b0c32da899ba2
Improve exception handling of REST user creation
[ { "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": "@@ -21,6 +21,7 @@ import org.jboss.resteasy.annotations.cache.NoCache;\nimport javax.ws.rs.NotFoundException;\nimport org.jboss.resteasy.spi.ResteasyProviderFactory;\nimport org.keycloak.common.ClientConnection;\n+import org.keycloak.common.util.ObjectUtil;\nimport org.keycloak.events.admin.OperationType;\nimport org.keycloak.events.admin.ResourceType;\nimport org.keycloak.models.Constants;\n@@ -31,6 +32,7 @@ import org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.utils.ModelToRepresentation;\nimport org.keycloak.models.utils.RepresentationToModel;\n+import org.keycloak.policy.PasswordPolicyNotMetException;\nimport org.keycloak.representations.idm.UserRepresentation;\nimport org.keycloak.services.ErrorResponse;\nimport org.keycloak.services.ForbiddenException;\n@@ -105,8 +107,13 @@ public class UsersResource {\npublic Response createUser(final UserRepresentation rep) {\nauth.users().requireManage();\n+ String username = rep.getUsername();\n+ if (ObjectUtil.isBlank(username)) {\n+ return ErrorResponse.error(\"User name is missing\", Response.Status.BAD_REQUEST);\n+ }\n+\n// Double-check duplicated username and email here due to federation\n- if (session.users().getUserByUsername(rep.getUsername(), realm) != null) {\n+ if (session.users().getUserByUsername(username, realm) != null) {\nreturn ErrorResponse.exists(\"User exists with same username\");\n}\nif (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed() && session.users().getUserByEmail(rep.getEmail(), realm) != null) {\n@@ -114,7 +121,7 @@ public class UsersResource {\n}\ntry {\n- UserModel user = session.users().addUser(realm, rep.getUsername());\n+ UserModel user = session.users().addUser(realm, username);\nSet<String> emptySet = Collections.emptySet();\nUserResource.updateUserFromRep(user, rep, emptySet, realm, session, false);\n@@ -131,12 +138,17 @@ public class UsersResource {\nsession.getTransactionManager().setRollbackOnly();\n}\nreturn ErrorResponse.exists(\"User exists with same username or email\");\n+ } catch (PasswordPolicyNotMetException e) {\n+ if (session.getTransactionManager().isActive()) {\n+ session.getTransactionManager().setRollbackOnly();\n+ }\n+ return ErrorResponse.error(\"Password policy not met\", Response.Status.BAD_REQUEST);\n} catch (ModelException me){\nif (session.getTransactionManager().isActive()) {\nsession.getTransactionManager().setRollbackOnly();\n}\nlogger.warn(\"Could not create user\", me);\n- return ErrorResponse.exists(\"Could not create user\");\n+ return ErrorResponse.error(\"Could not create user\", Response.Status.BAD_REQUEST);\n}\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": "@@ -438,6 +438,51 @@ public class UserTest extends AbstractAdminTest {\nassertEquals(user.getFederationLink(), createdUser.getFederationLink());\n}\n+ @Test\n+ public void createUserWithoutUsername() {\n+ UserRepresentation user = new UserRepresentation();\n+ user.setEmail(\"user1@localhost\");\n+ Response response = realm.users().create(user);\n+ assertEquals(400, response.getStatus());\n+ ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);\n+ Assert.assertEquals(\"User name is missing\", error.getErrorMessage());\n+ response.close();\n+ }\n+\n+ @Test\n+ public void createUserWithEmptyUsername() {\n+ UserRepresentation user = new UserRepresentation();\n+ user.setUsername(\"\");\n+ user.setEmail(\"user2@localhost\");\n+ Response response = realm.users().create(user);\n+ assertEquals(400, response.getStatus());\n+ ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);\n+ Assert.assertEquals(\"User name is missing\", error.getErrorMessage());\n+ response.close();\n+ }\n+\n+ @Test\n+ public void createUserWithInvalidPolicyPassword() {\n+ RealmRepresentation rep = realm.toRepresentation();\n+ String passwordPolicy = rep.getPasswordPolicy();\n+ rep.setPasswordPolicy(\"length(8)\");\n+ realm.update(rep);\n+ UserRepresentation user = new UserRepresentation();\n+ user.setUsername(\"user4\");\n+ user.setEmail(\"user4@localhost\");\n+ CredentialRepresentation rawPassword = new CredentialRepresentation();\n+ rawPassword.setValue(\"ABCD\");\n+ rawPassword.setType(CredentialRepresentation.PASSWORD);\n+ user.setCredentials(Arrays.asList(rawPassword));\n+ Response response = realm.users().create(user);\n+ assertEquals(400, response.getStatus());\n+ ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);\n+ Assert.assertEquals(\"Password policy not met\", error.getErrorMessage());\n+ rep.setPasswordPolicy(passwordPolicy);\n+ realm.update(rep);\n+ response.close();\n+ }\n+\nprivate List<String> createUsers() {\nList<String> ids = new ArrayList<>();\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-11511 Improve exception handling of REST user creation
339,187
14.01.2020 14:25:59
-3,600
72aff51fca203a1fc3f16ff88d0a3838c3563f20
inconsistent param name full to briefRepresentation
[ { "change_type": "MODIFY", "old_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/GroupsResource.java", "new_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/GroupsResource.java", "diff": "@@ -73,7 +73,7 @@ public interface GroupsResource {\n* @param search max number of occurrences\n* @param first index of the first element\n* @param max max number of occurrences\n- * @param fullRepresentation if true, return groups with their attributes\n+ * @param briefRepresentation if false, return groups with their attributes\n* @return A list containing the slice of all groups.\n*/\n@GET\n@@ -83,7 +83,7 @@ public interface GroupsResource {\nList<GroupRepresentation> groups(@QueryParam(\"search\") String search,\n@QueryParam(\"first\") Integer first,\n@QueryParam(\"max\") Integer max,\n- @QueryParam(\"full\") @DefaultValue(\"false\") boolean fullRepresentation);\n+ @QueryParam(\"briefRepresentation\") @DefaultValue(\"true\") boolean briefRepresentation);\n/**\n* Counts all groups.\n* @return A map containing key \"count\" with number of groups as value.\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/admin/GroupsResource.java", "new_path": "services/src/main/java/org/keycloak/services/resources/admin/GroupsResource.java", "diff": "@@ -75,17 +75,17 @@ public class GroupsResource {\npublic List<GroupRepresentation> getGroups(@QueryParam(\"search\") String search,\n@QueryParam(\"first\") Integer firstResult,\n@QueryParam(\"max\") Integer maxResults,\n- @QueryParam(\"full\") @DefaultValue(\"false\") boolean fullRepresentation) {\n+ @QueryParam(\"briefRepresentation\") @DefaultValue(\"true\") boolean briefRepresentation) {\nauth.groups().requireList();\nList<GroupRepresentation> results;\nif (Objects.nonNull(search)) {\n- results = ModelToRepresentation.searchForGroupByName(realm, fullRepresentation, search.trim(), firstResult, maxResults);\n+ results = ModelToRepresentation.searchForGroupByName(realm, !briefRepresentation, search.trim(), firstResult, maxResults);\n} else if(Objects.nonNull(firstResult) && Objects.nonNull(maxResults)) {\n- results = ModelToRepresentation.toGroupHierarchy(realm, fullRepresentation, firstResult, maxResults);\n+ results = ModelToRepresentation.toGroupHierarchy(realm, !briefRepresentation, firstResult, maxResults);\n} else {\n- results = ModelToRepresentation.toGroupHierarchy(realm, fullRepresentation);\n+ results = ModelToRepresentation.toGroupHierarchy(realm, !briefRepresentation);\n}\nreturn results;\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/admin/RoleContainerResource.java", "new_path": "services/src/main/java/org/keycloak/services/resources/admin/RoleContainerResource.java", "diff": "@@ -419,7 +419,7 @@ public class RoleContainerResource extends RoleResource {\n* @param roleName\n* @param firstResult\n* @param maxResults\n- * @param fullRepresentation if true, return a full representation of the GroupRepresentation objects\n+ * @param briefRepresentation if false, return a full representation of the GroupRepresentation objects\n* @return\n*/\n@Path(\"{role-name}/groups\")\n@@ -429,7 +429,7 @@ public class RoleContainerResource extends RoleResource {\npublic List<GroupRepresentation> getGroupsInRole(final @PathParam(\"role-name\") String roleName,\n@QueryParam(\"first\") Integer firstResult,\n@QueryParam(\"max\") Integer maxResults,\n- @QueryParam(\"full\") @DefaultValue(\"false\") boolean fullRepresentation) {\n+ @QueryParam(\"briefRepresentation\") @DefaultValue(\"true\") boolean briefRepresentation) {\nauth.roles().requireView(roleContainer);\nfirstResult = firstResult != null ? firstResult : 0;\n@@ -444,7 +444,7 @@ public class RoleContainerResource extends RoleResource {\nList<GroupModel> groupsModel = session.realms().getGroupsByRole(realm, role, firstResult, maxResults);\nreturn groupsModel.stream()\n- .map(g -> ModelToRepresentation.toRepresentation(g, fullRepresentation))\n+ .map(g -> ModelToRepresentation.toRepresentation(g, !briefRepresentation))\n.collect(Collectors.toList());\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/group/GroupTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/group/GroupTest.java", "diff": "@@ -690,7 +690,7 @@ public class GroupTest extends AbstractGroupTest {\ngroup.setAttributes(attributes);\ngroup = createGroup(realm, group);\n- List<GroupRepresentation> groups = groupsResource.groups(\"groupWithAttribute\", 0, 20, true);\n+ List<GroupRepresentation> groups = groupsResource.groups(\"groupWithAttribute\", 0, 20, false);\nassertFalse(groups.isEmpty());\nassertTrue(groups.get(0).getAttributes().containsKey(\"attribute1\"));\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12670 inconsistent param name full to briefRepresentation
339,187
08.01.2020 11:50:54
-3,600
789e8c70ceec8606894575beca457fee9e0428c2
full representation param for get groups by user endpoint
[ { "change_type": "MODIFY", "old_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/UserResource.java", "new_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/UserResource.java", "diff": "@@ -25,6 +25,7 @@ import org.keycloak.representations.idm.UserSessionRepresentation;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.DELETE;\n+import javax.ws.rs.DefaultValue;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.PUT;\n@@ -68,6 +69,19 @@ public interface UserResource {\n@QueryParam(\"first\") Integer firstResult,\n@QueryParam(\"max\") Integer maxResults);\n+ @Path(\"groups\")\n+ @GET\n+ List<GroupRepresentation> groups(@QueryParam(\"first\") Integer firstResult,\n+ @QueryParam(\"max\") Integer maxResults,\n+ @QueryParam(\"briefRepresentation\") @DefaultValue(\"true\") boolean briefRepresentation);\n+\n+ @Path(\"groups\")\n+ @GET\n+ List<GroupRepresentation> groups(@QueryParam(\"search\") String search,\n+ @QueryParam(\"first\") Integer firstResult,\n+ @QueryParam(\"max\") Integer maxResults,\n+ @QueryParam(\"briefRepresentation\") @DefaultValue(\"true\") boolean briefRepresentation);\n+\n@Path(\"groups/{groupId}\")\n@PUT\nvoid joinGroup(@PathParam(\"groupId\") String groupId);\n" }, { "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": "@@ -78,6 +78,7 @@ import org.keycloak.utils.ProfileHelper;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.DELETE;\n+import javax.ws.rs.DefaultValue;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.NotFoundException;\nimport javax.ws.rs.NotSupportedException;\n@@ -825,16 +826,17 @@ public class UserResource {\n@Produces(MediaType.APPLICATION_JSON)\npublic List<GroupRepresentation> groupMembership(@QueryParam(\"search\") String search,\n@QueryParam(\"first\") Integer firstResult,\n- @QueryParam(\"max\") Integer maxResults) {\n+ @QueryParam(\"max\") Integer maxResults,\n+ @QueryParam(\"briefRepresentation\") @DefaultValue(\"true\") boolean briefRepresentation) {\nauth.users().requireView(user);\nList<GroupRepresentation> results;\nif (Objects.nonNull(search) && Objects.nonNull(firstResult) && Objects.nonNull(maxResults)) {\n- results = ModelToRepresentation.searchForGroupByName(user, false, search.trim(), firstResult, maxResults);\n+ results = ModelToRepresentation.searchForGroupByName(user, !briefRepresentation, search.trim(), firstResult, maxResults);\n} else if(Objects.nonNull(firstResult) && Objects.nonNull(maxResults)) {\n- results = ModelToRepresentation.toGroupHierarchy(user, false, firstResult, maxResults);\n+ results = ModelToRepresentation.toGroupHierarchy(user, !briefRepresentation, firstResult, maxResults);\n} else {\n- results = ModelToRepresentation.toGroupHierarchy(user, false);\n+ results = ModelToRepresentation.toGroupHierarchy(user, !briefRepresentation);\n}\nreturn results;\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": "@@ -24,6 +24,8 @@ import org.jboss.arquillian.test.api.ArquillianResource;\nimport org.junit.Assert;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.keycloak.admin.client.resource.GroupResource;\n+import org.keycloak.admin.client.resource.GroupsResource;\nimport org.keycloak.admin.client.resource.IdentityProviderResource;\nimport org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.admin.client.resource.RoleMappingResource;\n@@ -43,6 +45,7 @@ import org.keycloak.representations.idm.ComponentRepresentation;\nimport org.keycloak.representations.idm.CredentialRepresentation;\nimport org.keycloak.representations.idm.ErrorRepresentation;\nimport org.keycloak.representations.idm.FederatedIdentityRepresentation;\n+import org.keycloak.representations.idm.GroupRepresentation;\nimport org.keycloak.representations.idm.IdentityProviderRepresentation;\nimport org.keycloak.representations.idm.MappingsRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\n@@ -59,9 +62,11 @@ import org.keycloak.testsuite.pages.LoginPage;\nimport org.keycloak.testsuite.pages.PageUtils;\nimport org.keycloak.testsuite.pages.ProceedPage;\nimport org.keycloak.testsuite.runonserver.RunHelpers;\n+import org.keycloak.testsuite.updaters.Creator;\nimport org.keycloak.testsuite.util.AdminEventPaths;\nimport org.keycloak.testsuite.util.ClientBuilder;\nimport org.keycloak.testsuite.util.GreenMailRule;\n+import org.keycloak.testsuite.util.GroupBuilder;\nimport org.keycloak.testsuite.util.MailUtils;\nimport org.keycloak.testsuite.util.OAuthClient;\nimport org.keycloak.testsuite.util.RealmBuilder;\n@@ -80,14 +85,17 @@ import java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\n+import java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\n+import java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.hasSize;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\n@@ -1728,4 +1736,33 @@ public class UserTest extends AbstractAdminTest {\nuser.resetPassword(credPasswd);\nAssert.assertEquals(1, user.credentials().size());\n}\n+\n+ @Test\n+ public void testGetGroupsForUserFullRepresentation() {\n+\n+ RealmResource realm = adminClient.realms().realm(\"test\");\n+\n+ String userName = \"averagejoe\";\n+ String groupName = \"groupWithAttribute\";\n+ Map<String, List<String>> attributes = new HashMap<String, List<String>>();\n+ attributes.put(\"attribute1\", Arrays.asList(\"attribute1\",\"attribute2\"));\n+\n+ UserRepresentation userRepresentation = UserBuilder\n+ .edit(createUserRepresentation(userName, \"[email protected]\", \"average\", \"joe\", true))\n+ .addPassword(\"password\")\n+ .build();\n+\n+ try (Creator<UserResource> u = Creator.create(realm, userRepresentation);\n+ Creator<GroupResource> g = Creator.create(realm, GroupBuilder.create().name(groupName).attributes(attributes).build())) {\n+\n+ String groupId = g.id();\n+ UserResource user = u.resource();\n+ user.joinGroup(groupId);\n+\n+ List<GroupRepresentation> userGroups = user.groups(0, 100, false);\n+\n+ assertFalse(userGroups.isEmpty());\n+ assertTrue(userGroups.get(0).getAttributes().containsKey(\"attribute1\"));\n+ }\n+ }\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12630 full representation param for get groups by user endpoint
339,192
20.06.2019 22:19:56
-32,400
562dc3ff8ce11fc459f976deb8233626d32c9228
Proxy authentication support for proxy-mappings
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/connections/httpclient/ProxyMappings.java", "new_path": "services/src/main/java/org/keycloak/connections/httpclient/ProxyMappings.java", "diff": "package org.keycloak.connections.httpclient;\nimport org.apache.http.HttpHost;\n+import org.apache.http.auth.UsernamePasswordCredentials;\n+import org.jboss.logging.Logger;\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n+import java.util.Map;\nimport java.util.Objects;\n+import java.util.concurrent.ConcurrentHashMap;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;\n@@ -36,10 +40,14 @@ import java.util.stream.Collectors;\n*/\npublic class ProxyMappings {\n+ private static final Logger logger = Logger.getLogger(ProxyMappings.class);\n+\nprivate static final ProxyMappings EMPTY_MAPPING = valueOf(Collections.emptyList());\nprivate final List<ProxyMapping> entries;\n+ private static Map<String, ProxyMapping> hostnameToProxyCache = new ConcurrentHashMap<>();\n+\n/**\n* Creates a {@link ProxyMappings} from the provided {@link ProxyMapping Entries}.\n*\n@@ -92,18 +100,28 @@ public class ProxyMappings {\n/**\n* @param hostname\n- * @return the {@link HttpHost} proxy associated with the first matching hostname {@link Pattern}\n- * or {@literal null} if none matches.\n+ * @return the {@link ProxyMapping} associated with the first matching hostname {@link Pattern}\n+ * or the {@link ProxyMapping} including {@literal null} as {@link HttpHost} if none matches.\n*/\n- public HttpHost getProxyFor(String hostname) {\n+ public ProxyMapping getProxyFor(String hostname) {\nObjects.requireNonNull(hostname, \"hostname\");\n-\n- return entries.stream() //\n+ if (hostnameToProxyCache.containsKey(hostname)) {\n+ return hostnameToProxyCache.get(hostname);\n+ }\n+ ProxyMapping proxyMapping = entries.stream() //\n.filter(e -> e.matches(hostname)) //\n.findFirst() //\n- .map(ProxyMapping::getProxy) //\n.orElse(null);\n+ if (proxyMapping == null) {\n+ proxyMapping = new ProxyMapping(null, null, null);\n+ }\n+ hostnameToProxyCache.put(hostname, proxyMapping);\n+ return proxyMapping;\n+ }\n+\n+ public static void clearCache() {\n+ hostnameToProxyCache.clear();\n}\n/**\n@@ -117,19 +135,26 @@ public class ProxyMappings {\nprivate final Pattern hostnamePattern;\n- private final HttpHost proxy;\n+ private final HttpHost proxyHost;\n- public ProxyMapping(Pattern hostnamePattern, HttpHost proxy) {\n+ private final UsernamePasswordCredentials proxyCredentials;\n+\n+ public ProxyMapping(Pattern hostnamePattern, HttpHost proxyHost, UsernamePasswordCredentials proxyCredentials) {\nthis.hostnamePattern = hostnamePattern;\n- this.proxy = proxy;\n+ this.proxyHost = proxyHost;\n+ this.proxyCredentials = proxyCredentials;\n}\npublic Pattern getHostnamePattern() {\nreturn hostnamePattern;\n}\n- public HttpHost getProxy() {\n- return proxy;\n+ public HttpHost getProxyHost() {\n+ return proxyHost;\n+ }\n+\n+ public UsernamePasswordCredentials getProxyCredentials() {\n+ return proxyCredentials;\n}\npublic boolean matches(String hostname) {\n@@ -166,26 +191,31 @@ public class ProxyMappings {\nString proxyUriString = mappingTokens[1];\nPattern hostPattern = Pattern.compile(hostPatternRegex);\n- HttpHost proxyHost = toProxyHost(proxyUriString);\n-\n- return new ProxyMapping(hostPattern, proxyHost);\n- }\n-\n- private static HttpHost toProxyHost(String proxyUriString) {\n-\nif (NO_PROXY.equals(proxyUriString)) {\n- return null;\n+ return new ProxyMapping(hostPattern, null, null);\n}\nURI uri = URI.create(proxyUriString);\n- return new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());\n+ String userInfo = uri.getUserInfo();\n+ UsernamePasswordCredentials proxyCredentials = null;\n+ if (userInfo != null) {\n+ if (userInfo.indexOf(\":\") > 0) {\n+ String[] credencials = userInfo.split(\":\", 2);\n+ if (credencials != null && credencials.length == 2) {\n+ proxyCredentials = new UsernamePasswordCredentials(credencials[0], credencials[1]);\n+ }\n+ } else {\n+ logger.warn(\"Invalid proxy credentials: \" + userInfo);\n+ }\n+ }\n+ return new ProxyMapping(hostPattern, new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), proxyCredentials);\n}\n@Override\npublic String toString() {\nreturn \"ProxyMapping{\" +\n\"hostnamePattern=\" + hostnamePattern +\n- \", proxy=\" + proxy +\n+ \", proxyHost=\" + proxyHost +\n'}';\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/connections/httpclient/ProxyMappingsAwareRoutePlanner.java", "new_path": "services/src/main/java/org/keycloak/connections/httpclient/ProxyMappingsAwareRoutePlanner.java", "diff": "@@ -19,11 +19,18 @@ package org.keycloak.connections.httpclient;\nimport org.apache.http.HttpException;\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpRequest;\n+import org.apache.http.auth.AuthScope;\n+import org.apache.http.auth.UsernamePasswordCredentials;\n+import org.apache.http.client.CredentialsProvider;\n+import org.apache.http.client.protocol.HttpClientContext;\n+import org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.conn.DefaultRoutePlanner;\nimport org.apache.http.impl.conn.DefaultSchemePortResolver;\nimport org.apache.http.protocol.HttpContext;\nimport org.jboss.logging.Logger;\n+import static org.keycloak.connections.httpclient.ProxyMappings.ProxyMapping;\n+\n/**\n* A {@link DefaultRoutePlanner} that determines the proxy to use for a given target hostname by consulting\n* the given {@link ProxyMappings}.\n@@ -45,9 +52,16 @@ public class ProxyMappingsAwareRoutePlanner extends DefaultRoutePlanner {\n@Override\nprotected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {\n- HttpHost proxy = proxyMappings.getProxyFor(target.getHostName());\n- LOG.debugf(\"Returning proxy=%s for targetHost=%s\", proxy, target.getHostName());\n-\n- return proxy;\n+ String targetHostName = target.getHostName();\n+ ProxyMapping proxyMapping = proxyMappings.getProxyFor(targetHostName);\n+ LOG.debugf(\"Returning proxyMapping=%s for targetHost=%s\", proxyMapping, targetHostName);\n+ UsernamePasswordCredentials proxyCredentials = proxyMapping.getProxyCredentials();\n+ HttpHost proxyHost = proxyMapping.getProxyHost();\n+ if (proxyCredentials != null) {\n+ CredentialsProvider credsProvider = new BasicCredentialsProvider();\n+ credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), proxyCredentials);\n+ context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);\n+ }\n+ return proxyHost;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/test/java/org/keycloak/connections/httpclient/ProxyMappingsTest.java", "new_path": "services/src/test/java/org/keycloak/connections/httpclient/ProxyMappingsTest.java", "diff": "*/\npackage org.keycloak.connections.httpclient;\n-import org.apache.http.HttpHost;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\n+import org.keycloak.connections.httpclient.ProxyMappings.ProxyMapping;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n@@ -47,6 +47,8 @@ public class ProxyMappingsTest {\nprivate static final List<String> MAPPINGS_WITH_FALLBACK_AND_PROXY_EXCEPTION = new ArrayList<>();\n+ private static final List<String> MAPPINGS_WITH_PROXY_AUTHENTICATION = new ArrayList<>();\n+\nstatic {\nMAPPINGS_WITH_FALLBACK.addAll(DEFAULT_MAPPINGS);\nMAPPINGS_WITH_FALLBACK.add(\".*;http://fallback:8080\");\n@@ -58,6 +60,11 @@ public class ProxyMappingsTest {\nMAPPINGS_WITH_FALLBACK_AND_PROXY_EXCEPTION.add(\".*;http://fallback:8080\");\n}\n+ static {\n+ MAPPINGS_WITH_PROXY_AUTHENTICATION.add(\".*stackexchange\\\\.com;http://user01:pas2w0rd@proxy3:88\");\n+ MAPPINGS_WITH_PROXY_AUTHENTICATION.addAll(MAPPINGS_WITH_FALLBACK_AND_PROXY_EXCEPTION);\n+ }\n+\n@Rule\npublic ExpectedException expectedException = ExpectedException.none();\n@@ -65,6 +72,7 @@ public class ProxyMappingsTest {\n@Before\npublic void setup() {\n+ ProxyMappings.clearCache();\nproxyMappings = ProxyMappings.valueOf(DEFAULT_MAPPINGS);\n}\n@@ -76,40 +84,40 @@ public class ProxyMappingsTest {\n@Test\npublic void shouldReturnProxy1ForConfiguredProxyMapping() {\n- HttpHost proxy = proxyMappings.getProxyFor(\"account.google.com\");\n- assertThat(proxy, is(notNullValue()));\n- assertThat(proxy.getHostName(), is(\"proxy1\"));\n+ ProxyMapping proxy = proxyMappings.getProxyFor(\"account.google.com\");\n+ assertThat(proxy.getProxyHost(), is(notNullValue()));\n+ assertThat(proxy.getProxyHost().getHostName(), is(\"proxy1\"));\n}\n@Test\npublic void shouldReturnProxy1ForConfiguredProxyMappingAlternative() {\n- HttpHost proxy = proxyMappings.getProxyFor(\"www.googleapis.com\");\n- assertThat(proxy, is(notNullValue()));\n- assertThat(proxy.getHostName(), is(\"proxy1\"));\n+ ProxyMapping proxy = proxyMappings.getProxyFor(\"www.googleapis.com\");\n+ assertThat(proxy.getProxyHost(), is(notNullValue()));\n+ assertThat(proxy.getProxyHost().getHostName(), is(\"proxy1\"));\n}\n@Test\npublic void shouldReturnProxy1ForConfiguredProxyMappingWithSubDomain() {\n- HttpHost proxy = proxyMappings.getProxyFor(\"awesome.account.google.com\");\n- assertThat(proxy, is(notNullValue()));\n- assertThat(proxy.getHostName(), is(\"proxy1\"));\n+ ProxyMapping proxy = proxyMappings.getProxyFor(\"awesome.account.google.com\");\n+ assertThat(proxy.getProxyHost(), is(notNullValue()));\n+ assertThat(proxy.getProxyHost().getHostName(), is(\"proxy1\"));\n}\n@Test\npublic void shouldReturnProxy2ForConfiguredProxyMapping() {\n- HttpHost proxy = proxyMappings.getProxyFor(\"login.facebook.com\");\n- assertThat(proxy, is(notNullValue()));\n- assertThat(proxy.getHostName(), is(\"proxy2\"));\n+ ProxyMapping proxy = proxyMappings.getProxyFor(\"login.facebook.com\");\n+ assertThat(proxy.getProxyHost(), is(notNullValue()));\n+ assertThat(proxy.getProxyHost().getHostName(), is(\"proxy2\"));\n}\n@Test\npublic void shouldReturnNoProxyForUnknownHost() {\n- HttpHost proxy = proxyMappings.getProxyFor(\"login.microsoft.com\");\n- assertThat(proxy, is(nullValue()));\n+ ProxyMapping proxy = proxyMappings.getProxyFor(\"login.microsoft.com\");\n+ assertThat(proxy.getProxyHost(), is(nullValue()));\n}\n@Test\n@@ -126,8 +134,8 @@ public class ProxyMappingsTest {\nProxyMappings proxyMappingsWithFallback = ProxyMappings.valueOf(MAPPINGS_WITH_FALLBACK);\n- HttpHost proxy = proxyMappingsWithFallback.getProxyFor(\"login.salesforce.com\");\n- assertThat(proxy.getHostName(), is(\"fallback\"));\n+ ProxyMapping proxy = proxyMappingsWithFallback.getProxyFor(\"login.salesforce.com\");\n+ assertThat(proxy.getProxyHost().getHostName(), is(\"fallback\"));\n}\n@Test\n@@ -135,17 +143,17 @@ public class ProxyMappingsTest {\nProxyMappings proxyMappingsWithFallback = ProxyMappings.valueOf(MAPPINGS_WITH_FALLBACK);\n- HttpHost forGoogle = proxyMappingsWithFallback.getProxyFor(\"login.google.com\");\n- assertThat(forGoogle.getHostName(), is(\"proxy1\"));\n+ ProxyMapping forGoogle = proxyMappingsWithFallback.getProxyFor(\"login.google.com\");\n+ assertThat(forGoogle.getProxyHost().getHostName(), is(\"proxy1\"));\n- HttpHost forFacebook = proxyMappingsWithFallback.getProxyFor(\"login.facebook.com\");\n- assertThat(forFacebook.getHostName(), is(\"proxy2\"));\n+ ProxyMapping forFacebook = proxyMappingsWithFallback.getProxyFor(\"login.facebook.com\");\n+ assertThat(forFacebook.getProxyHost().getHostName(), is(\"proxy2\"));\n- HttpHost forMicrosoft = proxyMappingsWithFallback.getProxyFor(\"login.microsoft.com\");\n- assertThat(forMicrosoft.getHostName(), is(\"fallback\"));\n+ ProxyMapping forMicrosoft = proxyMappingsWithFallback.getProxyFor(\"login.microsoft.com\");\n+ assertThat(forMicrosoft.getProxyHost().getHostName(), is(\"fallback\"));\n- HttpHost forSalesForce = proxyMappingsWithFallback.getProxyFor(\"login.salesforce.com\");\n- assertThat(forSalesForce.getHostName(), is(\"fallback\"));\n+ ProxyMapping forSalesForce = proxyMappingsWithFallback.getProxyFor(\"login.salesforce.com\");\n+ assertThat(forSalesForce.getProxyHost().getHostName(), is(\"fallback\"));\n}\n@Test\n@@ -153,19 +161,46 @@ public class ProxyMappingsTest {\nProxyMappings proxyMappingsWithFallbackAndProxyException = ProxyMappings.valueOf(MAPPINGS_WITH_FALLBACK_AND_PROXY_EXCEPTION);\n- HttpHost forGoogle = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.google.com\");\n- assertThat(forGoogle.getHostName(), is(\"proxy1\"));\n+ ProxyMapping forGoogle = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.google.com\");\n+ assertThat(forGoogle.getProxyHost().getHostName(), is(\"proxy1\"));\n+\n+ ProxyMapping forFacebook = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.facebook.com\");\n+ assertThat(forFacebook.getProxyHost().getHostName(), is(\"proxy2\"));\n+\n+ ProxyMapping forAcmeCorp = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"myapp.acme.corp.com\");\n+ assertThat(forAcmeCorp.getProxyHost(), is(nullValue()));\n+\n+ ProxyMapping forMicrosoft = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.microsoft.com\");\n+ assertThat(forMicrosoft.getProxyHost().getHostName(), is(\"fallback\"));\n+\n+ ProxyMapping forSalesForce = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.salesforce.com\");\n+ assertThat(forSalesForce.getProxyHost().getHostName(), is(\"fallback\"));\n+ }\n+\n+ @Test\n+ public void shouldReturnProxyAuthentication() {\n+\n+ ProxyMappings proxyMappingsWithProxyAuthen = ProxyMappings.valueOf(MAPPINGS_WITH_PROXY_AUTHENTICATION);\n+\n+ ProxyMapping forGoogle = proxyMappingsWithProxyAuthen.getProxyFor(\"login.google.com\");\n+ assertThat(forGoogle.getProxyHost().getHostName(), is(\"proxy1\"));\n+\n+ ProxyMapping forFacebook = proxyMappingsWithProxyAuthen.getProxyFor(\"login.facebook.com\");\n+ assertThat(forFacebook.getProxyHost().getHostName(), is(\"proxy2\"));\n- HttpHost forFacebook = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.facebook.com\");\n- assertThat(forFacebook.getHostName(), is(\"proxy2\"));\n+ ProxyMapping forStackOverflow = proxyMappingsWithProxyAuthen.getProxyFor(\"stackexchange.com\");\n+ assertThat(forStackOverflow.getProxyHost().getHostName(), is(\"proxy3\"));\n+ assertThat(forStackOverflow.getProxyHost().getPort(), is(88));\n+ assertThat(forStackOverflow.getProxyCredentials().getUserName(), is(\"user01\"));\n+ assertThat(forStackOverflow.getProxyCredentials().getPassword(), is(\"pas2w0rd\"));\n- HttpHost forAcmeCorp = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"myapp.acme.corp.com\");\n- assertThat(forAcmeCorp, is(nullValue()));\n+ ProxyMapping forAcmeCorp = proxyMappingsWithProxyAuthen.getProxyFor(\"myapp.acme.corp.com\");\n+ assertThat(forAcmeCorp.getProxyHost(), is(nullValue()));\n- HttpHost forMicrosoft = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.microsoft.com\");\n- assertThat(forMicrosoft.getHostName(), is(\"fallback\"));\n+ ProxyMapping forMicrosoft = proxyMappingsWithProxyAuthen.getProxyFor(\"login.microsoft.com\");\n+ assertThat(forMicrosoft.getProxyHost().getHostName(), is(\"fallback\"));\n- HttpHost forSalesForce = proxyMappingsWithFallbackAndProxyException.getProxyFor(\"login.salesforce.com\");\n- assertThat(forSalesForce.getHostName(), is(\"fallback\"));\n+ ProxyMapping forSalesForce = proxyMappingsWithProxyAuthen.getProxyFor(\"login.salesforce.com\");\n+ assertThat(forSalesForce.getProxyHost().getHostName(), is(\"fallback\"));\n}\n}\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-10659 Proxy authentication support for proxy-mappings
339,581
16.01.2020 09:11:25
-3,600
05c428f6e74de7a544587537cebeee35aae70eb4
After password reset, the new password has low priority
[ { "change_type": "MODIFY", "old_path": "common/src/main/java/org/keycloak/common/util/Time.java", "new_path": "common/src/main/java/org/keycloak/common/util/Time.java", "diff": "@@ -39,7 +39,7 @@ public class Time {\n* @return see description\n*/\npublic static long currentTimeMillis() {\n- return System.currentTimeMillis() + (offset * 1000);\n+ return System.currentTimeMillis() + (offset * 1000L);\n}\n/**\n@@ -48,7 +48,7 @@ public class Time {\n* @return see description\n*/\npublic static Date toDate(int time) {\n- return new Date(((long) time ) * 1000);\n+ return new Date(time * 1000L);\n}\n/**\n@@ -66,7 +66,7 @@ public class Time {\n* @return Time in milliseconds\n*/\npublic static long toMillis(int time) {\n- return ((long) time) * 1000;\n+ return time * 1000L;\n}\n/**\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java", "new_path": "services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java", "diff": "@@ -32,7 +32,6 @@ import org.keycloak.models.cache.UserCache;\nimport org.keycloak.policy.PasswordPolicyManagerProvider;\nimport org.keycloak.policy.PolicyError;\n-import java.io.IOException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Set;\n@@ -90,21 +89,46 @@ public class PasswordCredentialProvider implements CredentialProvider<PasswordCr\n@Override\npublic CredentialModel createCredential(RealmModel realm, UserModel user, PasswordCredentialModel credentialModel) {\n+\nPasswordPolicy policy = realm.getPasswordPolicy();\n- try {\n- expirePassword(realm, user, policy);\n+ int expiredPasswordsPolicyValue = policy.getExpiredPasswords();\n+\n+ // 1) create new or reset existing password\n+ CredentialModel createdCredential;\n+ CredentialModel oldPassword = getPassword(realm, user);\nif (credentialModel.getCreatedDate() == null) {\ncredentialModel.setCreatedDate(Time.currentTimeMillis());\n}\n- CredentialModel createdCredential = getCredentialStore().createCredential(realm, user, credentialModel);\n+ if (oldPassword == null) { // no password exists --> create new\n+ createdCredential = getCredentialStore().createCredential(realm, user, credentialModel);\n+ } else { // password exists --> update existing\n+ credentialModel.setId(oldPassword.getId());\n+ getCredentialStore().updateCredential(realm, user, credentialModel);\n+ createdCredential = credentialModel;\n+\n+ // 2) add a password history item based on the old password\n+ if (expiredPasswordsPolicyValue > 1) {\n+ oldPassword.setId(null);\n+ oldPassword.setType(PasswordCredentialModel.PASSWORD_HISTORY);\n+ getCredentialStore().createCredential(realm, user, oldPassword);\n+ }\n+ }\n+\n+ // 3) remove old password history items\n+ List<CredentialModel> passwordHistoryList = getCredentialStore().getStoredCredentialsByType(realm, user, PasswordCredentialModel.PASSWORD_HISTORY);\n+ final int passwordHistoryListMaxSize = Math.max(0, expiredPasswordsPolicyValue - 1);\n+ if (passwordHistoryList.size() > passwordHistoryListMaxSize) {\n+ passwordHistoryList.stream()\n+ .sorted(CredentialModel.comparingByStartDateDesc())\n+ .skip(passwordHistoryListMaxSize)\n+ .forEach(p -> getCredentialStore().removeStoredCredential(realm, user, p.getId()));\n+ }\n+\nUserCache userCache = session.userCache();\nif (userCache != null) {\nuserCache.evict(realm, user);\n}\nreturn createdCredential;\n- } catch (IOException e) {\n- throw new RuntimeException(e);\n- }\n}\n@Override\n@@ -118,31 +142,6 @@ public class PasswordCredentialProvider implements CredentialProvider<PasswordCr\n}\n- protected void expirePassword(RealmModel realm, UserModel user, PasswordPolicy policy) throws IOException {\n-\n- CredentialModel oldPassword = getPassword(realm, user);\n- if (oldPassword == null) return;\n- int expiredPasswordsPolicyValue = policy.getExpiredPasswords();\n- List<CredentialModel> list = getCredentialStore().getStoredCredentialsByType(realm, user, PasswordCredentialModel.PASSWORD_HISTORY);\n- if (expiredPasswordsPolicyValue > 1) {\n- // oldPassword will expire few lines below, and there is one active password,\n- // hence (expiredPasswordsPolicyValue - 2) passwords should be left in history\n- final int passwordsToLeave = expiredPasswordsPolicyValue - 2;\n- if (list.size() > passwordsToLeave) {\n- list.stream()\n- .sorted(CredentialModel.comparingByStartDateDesc())\n- .skip(passwordsToLeave)\n- .forEach(p -> getCredentialStore().removeStoredCredential(realm, user, p.getId()));\n- }\n- oldPassword.setType(PasswordCredentialModel.PASSWORD_HISTORY);\n- getCredentialStore().updateCredential(realm, user, oldPassword);\n- } else {\n- list.stream().forEach(p -> getCredentialStore().removeStoredCredential(realm, user, p.getId()));\n- getCredentialStore().removeStoredCredential(realm, user, oldPassword.getId());\n- }\n-\n- }\n-\nprotected PasswordHashProvider getHashProvider(PasswordPolicy policy) {\nPasswordHashProvider hash = session.getProvider(PasswordHashProvider.class, policy.getHashAlgorithm());\nif (hash == null) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordHistoryPolicyTest.java", "diff": "+/*\n+ * Copyright 2016 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.policy;\n+\n+import java.util.function.Consumer;\n+import javax.ws.rs.BadRequestException;\n+import javax.ws.rs.core.Response;\n+import org.junit.After;\n+import org.junit.Before;\n+import org.junit.Ignore;\n+import org.junit.Test;\n+import org.keycloak.admin.client.resource.UserResource;\n+import org.keycloak.representations.idm.CredentialRepresentation;\n+import org.keycloak.representations.idm.RealmRepresentation;\n+import org.keycloak.representations.idm.UserRepresentation;\n+import org.keycloak.testsuite.AbstractAuthTest;\n+\n+import static org.keycloak.representations.idm.CredentialRepresentation.PASSWORD;\n+import static org.keycloak.testsuite.admin.ApiUtil.getCreatedId;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Tomas Kyjovsky</a>\n+ */\n+public class PasswordHistoryPolicyTest extends AbstractAuthTest {\n+\n+ UserResource user;\n+\n+ private void setPasswordHistory(String passwordHistory) {\n+ log.info(String.format(\"Setting %s\", passwordHistory));\n+ RealmRepresentation testRealmRepresentation = testRealmResource().toRepresentation();\n+ testRealmRepresentation.setPasswordPolicy(passwordHistory);\n+ testRealmResource().update(testRealmRepresentation);\n+ }\n+\n+ private void setPasswordHistoryValue(String value) {\n+ setPasswordHistory(String.format(\"passwordHistory(%s)\", value));\n+ }\n+\n+ private void setPasswordHistoryValue(int value) {\n+ setPasswordHistoryValue(String.valueOf(value));\n+ }\n+\n+ public UserRepresentation createUserRepresentation(String username) {\n+ UserRepresentation userRepresentation = new UserRepresentation();\n+ userRepresentation.setUsername(username);\n+ userRepresentation.setEmail(String.format(\"%[email protected]\", userRepresentation.getUsername()));\n+ userRepresentation.setEmailVerified(true);\n+ return userRepresentation;\n+ }\n+\n+ public UserResource createUser(UserRepresentation user) {\n+ String createdUserId;\n+ try (Response response = testRealmResource().users().create(user)) {\n+ createdUserId = getCreatedId(response);\n+ }\n+ return testRealmResource().users().get(createdUserId);\n+ }\n+\n+ public void resetUserPassword(UserResource userResource, String newPassword) {\n+ CredentialRepresentation newCredential = new CredentialRepresentation();\n+ newCredential.setType(PASSWORD);\n+ newCredential.setValue(newPassword);\n+ newCredential.setTemporary(false);\n+ userResource.resetPassword(newCredential);\n+ }\n+\n+ private void expectBadRequestException(Consumer<Void> f) {\n+ try {\n+ f.accept(null);\n+ throw new AssertionError(\"An expected BadRequestException was not thrown.\");\n+ } catch (BadRequestException bre) {\n+ log.info(\"An expected BadRequestException was caught.\");\n+ }\n+ }\n+\n+ @Before\n+ public void before() {\n+ user = createUser(createUserRepresentation(\"test_user\"));\n+ }\n+\n+ @After\n+ public void after() {\n+ user.remove();\n+ }\n+\n+ @Test\n+ public void testPasswordHistory_noHistory() {\n+ setPasswordHistory(\"\");\n+ resetUserPassword(user, \"secret\"); // history:\n+ resetUserPassword(user, \"secret\"); // history:\n+ }\n+\n+ @Test\n+ public void testPasswordHistory_length1() {\n+ setPasswordHistoryValue(1);\n+ resetUserPassword(user, \"secret\"); // history: secret\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret\");\n+ });\n+ resetUserPassword(user, \"secret_2\"); // history: secret_2\n+ }\n+\n+ @Test\n+ public void testPasswordHistory_length2() {\n+ setPasswordHistoryValue(2);\n+ resetUserPassword(user, \"secret\"); // history: secret\n+ resetUserPassword(user, \"secret_2\"); // history: secret_2, secret\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_2\");\n+ });\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret\");\n+ });\n+ resetUserPassword(user, \"secret_3\"); // history: secret_3, secret_2\n+\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_3\");\n+ });\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_2\");\n+ });\n+ resetUserPassword(user, \"secret\"); // history: secret, secret_3\n+ }\n+\n+ @Test\n+ public void testPasswordHistory_length3() {\n+ setPasswordHistoryValue(3);\n+ resetUserPassword(user, \"secret\"); // history: secret\n+ resetUserPassword(user, \"secret_2\"); // history: secret_2, secret\n+ resetUserPassword(user, \"secret_3\"); // history: secret_3, secret_2, secret\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_3\");\n+ });\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_2\");\n+ });\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret\");\n+ });\n+ resetUserPassword(user, \"secret_4\"); // history: secret_4, secret_3, secret_2\n+\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_4\");\n+ });\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_3\");\n+ });\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_2\");\n+ });\n+ resetUserPassword(user, \"secret\"); // history: secret, secret_4, secret_3\n+ }\n+\n+ @Test\n+ public void testPasswordHistory_lengthChange() {\n+ testPasswordHistory_length3(); // history: secret, secret_4, secret_3\n+\n+ setPasswordHistoryValue(2); // history: secret, secret_4\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret\");\n+ });\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_4\");\n+ });\n+ resetUserPassword(user, \"secret_2\"); // history: secret_2, secret\n+\n+ setPasswordHistoryValue(1); // history: secret_2\n+ expectBadRequestException(f -> {\n+ resetUserPassword(user, \"secret_2\");\n+ });\n+ resetUserPassword(user, \"secret\"); // history: secret\n+\n+ setPasswordHistory(\"\"); // history:\n+ resetUserPassword(user, \"secret\"); // history:\n+ }\n+\n+ @Test\n+ public void testInvalidPasswordHistoryPolicyValue_notANumber() {\n+ expectBadRequestException(f -> {\n+ setPasswordHistoryValue(\"abc\");\n+ });\n+ expectBadRequestException(f -> {\n+ setPasswordHistoryValue(\"2-\");\n+ });\n+ expectBadRequestException(f -> {\n+ setPasswordHistoryValue(\"-2-\");\n+ });\n+ }\n+\n+ @Test\n+ @Ignore(\"KEYCLOAK-12673\")\n+ public void testInvalidPasswordHistoryPolicyValue_zero() {\n+ expectBadRequestException(f -> {\n+ setPasswordHistoryValue(0);\n+ });\n+ }\n+\n+ @Test\n+ @Ignore(\"KEYCLOAK-12673\")\n+ public void testInvalidPasswordHistoryPolicyValue_negative() {\n+ expectBadRequestException(f -> {\n+ setPasswordHistoryValue(-1);\n+ });\n+ expectBadRequestException(f -> {\n+ setPasswordHistoryValue(-2);\n+ });\n+ expectBadRequestException(f -> {\n+ setPasswordHistoryValue(-10);\n+ });\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/authentication/PasswordPolicyTest.java", "new_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/authentication/PasswordPolicyTest.java", "diff": "@@ -166,7 +166,6 @@ public class PasswordPolicyTest extends AbstractConsoleTest {\n}\n@Test\n- @Ignore(\"Disabled until KEYCLOAK-11922 is resolved.\")\npublic void testPasswordHistoryPolicy() {\nRealmRepresentation realm = testRealmResource().toRepresentation();\nrealm.setPasswordPolicy(\"passwordHistory(2)\");\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12295 After password reset, the new password has low priority (#6653)
339,465
17.12.2019 14:55:06
-3,600
85dc1b36537d0c4263fcb78936d009e281473129
Add username to the login form + ability to reset login - NOT DESIGN YET
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/DefaultAuthenticationFlow.java", "new_path": "services/src/main/java/org/keycloak/authentication/DefaultAuthenticationFlow.java", "diff": "@@ -101,7 +101,7 @@ public class DefaultAuthenticationFlow implements AuthenticationFlow {\n// User clicked on \"try another way\" link\nif (inputData.containsKey(\"tryAnotherWay\")) {\n- logger.info(\"User clicked on try another way\");\n+ logger.trace(\"User clicked on link 'Try Another Way'\");\nList<AuthenticationSelectionOption> selectionOptions = createAuthenticationSelectionList(model);\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/forms/login/freemarker/model/AuthenticationContextBean.java", "new_path": "services/src/main/java/org/keycloak/forms/login/freemarker/model/AuthenticationContextBean.java", "diff": "@@ -23,6 +23,7 @@ import java.util.List;\nimport org.keycloak.authentication.AuthenticationFlowContext;\nimport org.keycloak.authentication.AuthenticationSelectionOption;\n+import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;\nimport org.keycloak.forms.login.LoginFormsPages;\n/**\n@@ -45,4 +46,23 @@ public class AuthenticationContextBean {\npublic boolean showTryAnotherWayLink() {\nreturn getAuthenticationSelections().size() > 1 && page != LoginFormsPages.LOGIN_SELECT_AUTHENTICATOR;\n}\n+\n+\n+ public boolean showUsername() {\n+ return context != null && context.getUser() != null && context.getAuthenticationSession() != null;\n+ }\n+\n+\n+ // NOTE: This is called \"attemptedUsername\" as we won't necessarily display the username of the user, but the \"attempted username\", which he\n+ // used on the login screen (which could be eventually email or something else)\n+ public String getAttemptedUsername() {\n+ String username = context.getAuthenticationSession().getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);\n+\n+ // Fallback to real username of the user just if attemptedUsername doesn't exists\n+ if (username == null) {\n+ username = context.getUser().getUsername();\n+ }\n+\n+ return username;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java", "diff": "@@ -22,6 +22,7 @@ import org.keycloak.testsuite.util.DroneUtils;\nimport org.keycloak.testsuite.util.WaitUtils;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.NoSuchElementException;\n+import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.support.FindBy;\n@@ -41,6 +42,13 @@ public abstract class LanguageComboboxAwarePage extends AbstractPage {\n@FindBy(id = \"try-another-way\")\nprivate WebElement tryAnotherWayLink;\n+ @FindBy(id = \"attempted-username\")\n+ private WebElement attemptedUsernameLabel;\n+\n+ // TODO: This won't be a link, but some kind of an icon once we do better design\n+ @FindBy(id = \"reset-login\")\n+ private WebElement resetLoginLink;\n+\npublic String getLanguageDropdownText() {\nreturn languageText.getText();\n}\n@@ -65,4 +73,28 @@ public abstract class LanguageComboboxAwarePage extends AbstractPage {\npublic void clickTryAnotherWayLink() {\ntryAnotherWayLink.click();\n}\n+\n+\n+ // If false, we don't expect \"attempted username\" link available on the page. If true, we expect that it is available on the page\n+ public void assertAttemptedUsernameAvailability(boolean expectedAvailability) {\n+ assertAttemptedUsernameAvailability(driver, expectedAvailability);\n+ }\n+\n+ public static void assertAttemptedUsernameAvailability(WebDriver driver, boolean expectedAvailability) {\n+ try {\n+ driver.findElement(By.id(\"attempted-username\"));\n+ Assert.assertTrue(expectedAvailability);\n+ } catch (NoSuchElementException nse) {\n+ Assert.assertFalse(expectedAvailability);\n+ }\n+ }\n+\n+ public String getAttemptedUsername() {\n+ return attemptedUsernameLabel.getText();\n+ }\n+\n+\n+ public void clickResetLogin() {\n+ resetLoginLink.click();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java", "diff": "@@ -43,6 +43,7 @@ import org.keycloak.testsuite.admin.ApiUtil;\nimport org.keycloak.testsuite.pages.AccountTotpPage;\nimport org.keycloak.testsuite.pages.AppPage;\nimport org.keycloak.testsuite.pages.AppPage.RequestType;\n+import org.keycloak.testsuite.pages.LanguageComboboxAwarePage;\nimport org.keycloak.testsuite.pages.LoginConfigTotpPage;\nimport org.keycloak.testsuite.pages.LoginPage;\nimport org.keycloak.testsuite.pages.LoginTotpPage;\n@@ -136,6 +137,9 @@ public class RequiredActionTotpSetupTest extends AbstractTestRealmKeycloakTest {\nassertTrue(totpPage.isCurrent());\nassertFalse(totpPage.isCancelDisplayed());\n+ // assert attempted-username not shown when setup TOTP\n+ LanguageComboboxAwarePage.assertAttemptedUsernameAvailability(driver, false);\n+\n// KEYCLOAK-11753 - Verify OTP label element present on \"Configure OTP\" required action form\ndriver.findElement(By.id(\"userLabel\"));\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java", "diff": "@@ -12,6 +12,7 @@ import org.keycloak.testsuite.admin.ApiUtil;\nimport org.keycloak.testsuite.pages.PasswordPage;\nimport org.keycloak.testsuite.pages.SelectAuthenticatorPage;\nimport org.keycloak.testsuite.util.UserBuilder;\n+import org.keycloak.testsuite.util.WaitUtils;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java", "diff": "@@ -160,4 +160,26 @@ public class LoginTotpTest extends AbstractTestRealmKeycloakTest {\n.removeDetail(Details.CONSENT)\n.assertEvent();\n}\n+\n+\n+ @Test\n+ public void loginWithTotp_testAttemptedUsernameAndResetLogin() throws Exception {\n+ loginPage.open();\n+\n+ // Assert attempted-username NOT available\n+ loginPage.assertAttemptedUsernameAvailability(false);\n+\n+ loginPage.login(\"test-user@localhost\", \"password\");\n+\n+ Assert.assertTrue(loginTotpPage.isCurrent());\n+\n+ // Assert attempted-username available\n+ loginPage.assertAttemptedUsernameAvailability(true);\n+ Assert.assertEquals(\"test-user@localhost\", loginPage.getAttemptedUsername());\n+\n+ // Reset login and assert back on the login screen\n+ loginTotpPage.clickResetLogin();\n+\n+ loginPage.assertCurrent();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultiFactorAuthenticationTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultiFactorAuthenticationTest.java", "diff": "@@ -288,4 +288,53 @@ public class MultiFactorAuthenticationTest extends AbstractTestRealmKeycloakTest\n}\n}\n+\n+ // In a sub-flow with alternative credential executors, check the username of the user is shown on the login screen.\n+ // Also test the \"reset login\" link/icon .\n+ @Test\n+ public void testUsernameLabelAndResetLogin() {\n+ try {\n+ configureBrowserFlowWithAlternativeCredentials();\n+\n+ // The \"attempted username\" with username not yet available on the login screen\n+ loginUsernameOnlyPage.open();\n+ loginUsernameOnlyPage.assertAttemptedUsernameAvailability(false);\n+\n+ loginUsernameOnlyPage.login(\"user-with-one-configured-otp\");\n+\n+ // On the password page, username should be shown as we know the user\n+ passwordPage.assertCurrent();\n+ passwordPage.assertAttemptedUsernameAvailability(true);\n+ Assert.assertEquals(\"user-with-one-configured-otp\", passwordPage.getAttemptedUsername());\n+ passwordPage.clickTryAnotherWayLink();\n+\n+ // On the select-authenticator page, username should be shown as we know the user\n+ selectAuthenticatorPage.assertCurrent();\n+ selectAuthenticatorPage.assertAttemptedUsernameAvailability(true);\n+ Assert.assertEquals(\"user-with-one-configured-otp\", passwordPage.getAttemptedUsername());\n+\n+ // Reset login\n+ selectAuthenticatorPage.clickResetLogin();\n+\n+ // Should be back on the login page\n+ loginUsernameOnlyPage.assertCurrent();\n+\n+ // Use email as username. The email should be shown instead of username on the screens\n+ loginUsernameOnlyPage.assertAttemptedUsernameAvailability(false);\n+ loginUsernameOnlyPage.login(\"[email protected]\");\n+\n+ // On the password page, the email of user should be shown\n+ passwordPage.assertCurrent();\n+ passwordPage.assertAttemptedUsernameAvailability(true);\n+ Assert.assertEquals(\"[email protected]\", passwordPage.getAttemptedUsername());\n+\n+ // Login\n+ passwordPage.login(\"password\");\n+ events.expectLogin().user(testRealm().users().search(\"user-with-one-configured-otp\").get(0).getId())\n+ .detail(Details.USERNAME, \"[email protected]\").assertEvent();\n+ } finally {\n+ BrowserFlowTest.revertFlows(testRealm(), \"browser - alternative\");\n+ }\n+ }\n+\n}\n" }, { "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": "</div>\n</#if>\n+ <#if auth?has_content && auth.showUsername() >\n+ <div class=\"${properties.kcFormGroupClass!}\">\n+ <label id=\"attempted-username\">${auth.attemptedUsername}</label>\n+ <a href=\"${url.loginRestartFlowUrl}\" id=\"reset-login\">Reset Login</a>\n+ </div>\n+\n+ <hr />\n+\n+ </#if>\n+\n<#nested \"form\">\n<#if auth?has_content && auth.showTryAnotherWayLink() >\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12426 Add username to the login form + ability to reset login - NOT DESIGN YET
339,167
15.01.2020 12:41:42
-3,600
d3f6937a2346c7bfdef35785afef8cbff2b45dba
Add username to the login form + ability to reset login
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java", "diff": "@@ -191,12 +191,7 @@ public abstract class AbstractUsernameFormAuthenticator extends AbstractFormAuth\npublic boolean validatePassword(AuthenticationFlowContext context, UserModel user, MultivaluedMap<String, String> inputData, boolean clearUser) {\nString password = inputData.getFirst(CredentialRepresentation.PASSWORD);\nif (password == null || password.isEmpty()) {\n- context.getEvent().user(user);\n- context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);\n- Response challengeResponse = challenge(context, getDefaultChallengeMessage(context));\n- context.forceChallenge(challengeResponse);\n- context.clearUser();\n- return false;\n+ return badPasswordHandler(context, user, clearUser,true);\n}\nif (isTemporarilyDisabledByBruteForce(context, user)) return false;\n@@ -204,17 +199,26 @@ public abstract class AbstractUsernameFormAuthenticator extends AbstractFormAuth\nif (password != null && !password.isEmpty() && context.getSession().userCredentialManager().isValid(context.getRealm(), user, UserCredentialModel.password(password))) {\nreturn true;\n} else {\n+ return badPasswordHandler(context, user, clearUser,false);\n+ }\n+ }\n+\n+ // Set up AuthenticationFlowContext error.\n+ private boolean badPasswordHandler(AuthenticationFlowContext context, UserModel user, boolean clearUser,boolean isEmptyPassword) {\ncontext.getEvent().user(user);\ncontext.getEvent().error(Errors.INVALID_USER_CREDENTIALS);\nResponse challengeResponse = challenge(context, getDefaultChallengeMessage(context));\n+ if(isEmptyPassword) {\n+ context.forceChallenge(challengeResponse);\n+ }else{\ncontext.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challengeResponse);\n+ }\n+\nif (clearUser) {\ncontext.clearUser();\n}\nreturn false;\n}\n- }\n-\nprotected boolean isTemporarilyDisabledByBruteForce(AuthenticationFlowContext context, UserModel user) {\nif (context.getRealm().isBruteForceProtected()) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/forms/login/freemarker/model/AuthenticationContextBean.java", "new_path": "services/src/main/java/org/keycloak/forms/login/freemarker/model/AuthenticationContextBean.java", "diff": "@@ -49,7 +49,11 @@ public class AuthenticationContextBean {\npublic boolean showUsername() {\n- return context != null && context.getUser() != null && context.getAuthenticationSession() != null;\n+ return context != null && context.getUser() != null && context.getAuthenticationSession() != null && page!=LoginFormsPages.ERROR;\n+ }\n+\n+ public boolean showResetCredentials() {\n+ return showUsername() && page == LoginFormsPages.LOGIN_RESET_PASSWORD;\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java", "diff": "@@ -42,7 +42,7 @@ public abstract class LanguageComboboxAwarePage extends AbstractPage {\n@FindBy(id = \"try-another-way\")\nprivate WebElement tryAnotherWayLink;\n- @FindBy(id = \"attempted-username\")\n+ @FindBy(id = \"kc-attempted-username\")\nprivate WebElement attemptedUsernameLabel;\n// TODO: This won't be a link, but some kind of an icon once we do better design\n@@ -82,7 +82,7 @@ public abstract class LanguageComboboxAwarePage extends AbstractPage {\npublic static void assertAttemptedUsernameAvailability(WebDriver driver, boolean expectedAvailability) {\ntry {\n- driver.findElement(By.id(\"attempted-username\"));\n+ driver.findElement(By.id(\"kc-attempted-username\"));\nAssert.assertTrue(expectedAvailability);\n} catch (NoSuchElementException nse) {\nAssert.assertFalse(expectedAvailability);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginConfigTotpPage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginConfigTotpPage.java", "diff": "*/\npackage org.keycloak.testsuite.pages;\n+import org.openqa.selenium.By;\nimport org.openqa.selenium.NoSuchElementException;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.support.FindBy;\n@@ -73,7 +74,12 @@ public class LoginConfigTotpPage extends AbstractPage {\n}\npublic boolean isCurrent() {\n- return PageUtils.getPageTitle(driver).equals(\"Mobile Authenticator Setup\");\n+ try {\n+ driver.findElement(By.id(\"totp\"));\n+ return true;\n+ } catch (Throwable t) {\n+ return false;\n+ }\n}\npublic void open() {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginPasswordResetPage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginPasswordResetPage.java", "diff": "@@ -40,6 +40,7 @@ public class LoginPasswordResetPage extends LanguageComboboxAwarePage {\nprivate WebElement backToLogin;\npublic void changePassword(String username) {\n+ usernameInput.clear();\nusernameInput.sendKeys(username);\nsubmitButton.click();\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java", "diff": "@@ -58,15 +58,13 @@ public class LoginTotpPage extends LanguageComboboxAwarePage {\n}\npublic boolean isCurrent() {\n- if (driver.getTitle().startsWith(\"Log in to \")) {\ntry {\ndriver.findElement(By.id(\"otp\"));\nreturn true;\n} catch (Throwable t) {\n- }\n- }\nreturn false;\n}\n+ }\n@Override\npublic void open() {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/PasswordPage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/PasswordPage.java", "diff": "@@ -57,11 +57,6 @@ public class PasswordPage extends LanguageComboboxAwarePage {\n}\npublic boolean isCurrent(String realm) {\n- // Check the title\n- if (!DroneUtils.getCurrentDriver().getTitle().equals(\"Log in to \" + realm) && !DroneUtils.getCurrentDriver().getTitle().equals(\"Anmeldung bei \" + realm)) {\n- return false;\n- }\n-\n// Check there is NO username field\ntry {\ndriver.findElement(By.id(\"username\"));\n@@ -72,6 +67,7 @@ public class PasswordPage extends LanguageComboboxAwarePage {\n// Check there is password field\ntry {\n+ driver.findElement(By.id(\"kc-attempted-username\"));\ndriver.findElement(By.id(\"password\"));\n} catch (NoSuchElementException nfe) {\nreturn false;\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/SelectAuthenticatorPage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/SelectAuthenticatorPage.java", "diff": "@@ -3,7 +3,6 @@ package org.keycloak.testsuite.pages;\nimport java.util.List;\nimport java.util.stream.Collectors;\n-import org.junit.Assert;\nimport org.keycloak.testsuite.util.DroneUtils;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.NoSuchElementException;\n@@ -35,11 +34,7 @@ public class SelectAuthenticatorPage extends LanguageComboboxAwarePage {\n.stream()\n.filter(webElement -> webElement.getAttribute(\"selected\") != null)\n.findFirst()\n- .orElseThrow(() -> {\n-\n- return new AssertionError(\"Selected login method not found\");\n-\n- })\n+ .orElseThrow(() -> new AssertionError(\"Selected login method not found\"))\n.getText();\n}\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/login/login-reset-password.ftl", "new_path": "themes/src/main/resources/theme/base/login/login-reset-password.ftl", "diff": "<label for=\"username\" class=\"${properties.kcLabelClass!}\"><#if !realm.loginWithEmailAllowed>${msg(\"username\")}<#elseif !realm.registrationEmailAsUsername>${msg(\"usernameOrEmail\")}<#else>${msg(\"email\")}</#if></label>\n</div>\n<div class=\"${properties.kcInputWrapperClass!}\">\n+ <#if auth?has_content && auth.showUsername()>\n+ <input type=\"text\" id=\"username\" name=\"username\" class=\"${properties.kcInputClass!}\" autofocus value=\"${auth.attemptedUsername}\"/>\n+ <#else>\n<input type=\"text\" id=\"username\" name=\"username\" class=\"${properties.kcInputClass!}\" autofocus/>\n+ </#if>\n</div>\n</div>\n-\n<div class=\"${properties.kcFormGroupClass!} ${properties.kcFormSettingClass!}\">\n<div id=\"kc-form-options\" class=\"${properties.kcFormOptionsClass!}\">\n<div class=\"${properties.kcFormOptionsWrapperClass!}\">\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/login/messages/messages_en.properties", "new_path": "themes/src/main/resources/theme/base/login/messages/messages_en.properties", "diff": "@@ -83,6 +83,8 @@ offlineAccessScopeConsentText=Offline Access\nsamlRoleListScopeConsentText=My Roles\nrolesScopeConsentText=User roles\n+restartLoginTooltip=Restart login\n+\nloginTotpIntro=You need to set up a One Time Password generator to access this account\nloginTotpStep1=Install one of the following applications on your mobile\nloginTotpStep2=Open the application and scan the barcode\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/login/select-authenticator.ftl", "new_path": "themes/src/main/resources/theme/base/login/select-authenticator.ftl", "diff": "<#import \"template.ftl\" as layout>\n<@layout.registrationLayout displayInfo=true; section>\n- <#if section = \"header\">\n+ <#if section = \"header\" || section = \"show-username\">\n<script type=\"text/javascript\">\n// Fill up the two hidden and submit the form\nfunction fillAndSubmit() {\n" }, { "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": "</div>\n</div>\n</#if>\n+ <#if !(auth?has_content && auth.showUsername() && !auth.showResetCredentials())>\n<h1 id=\"kc-page-title\"><#nested \"header\"></h1>\n+ <#else>\n+ <#nested \"show-username\">\n+ </#if>\n</header>\n<div id=\"kc-content\">\n<div id=\"kc-content-wrapper\">\n+ <#if auth?has_content && auth.showUsername() && !auth.showResetCredentials()>\n+ <div class=\"${properties.kcFormGroupClass!}\">\n+ <div id=\"kc-username\">\n+ <label id=\"kc-attempted-username\">${auth.attemptedUsername}</label>\n+ <a id=\"reset-login\" href=\"${url.loginRestartFlowUrl}\">\n+ <div class=\"kc-login-tooltip\">\n+ <i class=\"${properties.kcResetFlowIcon!}\"></i>\n+ <span class=\"kc-tooltip-text\">${msg(\"restartLoginTooltip\")}</span>\n+ </div>\n+ </a>\n+ </div>\n+ </div>\n+ <hr/>\n+ </#if>\n+\n<#-- App-initiated actions should not see warning messages about the need to complete the action -->\n<#-- during login. -->\n<#if displayMessage && message?has_content && (message.type != 'warning' || !isAppInitiatedAction??)>\n</div>\n</#if>\n- <#if auth?has_content && auth.showUsername() >\n- <div class=\"${properties.kcFormGroupClass!}\">\n- <label id=\"attempted-username\">${auth.attemptedUsername}</label>\n- <a href=\"${url.loginRestartFlowUrl}\" id=\"reset-login\">Reset Login</a>\n- </div>\n-\n- <hr />\n-\n- </#if>\n-\n<#nested \"form\">\n<#if auth?has_content && auth.showTryAnotherWayLink() >\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak/login/resources/css/login.css", "new_path": "themes/src/main/resources/theme/keycloak/login/resources/css/login.css", "diff": "@@ -116,6 +116,17 @@ div.kc-logo-text span {\nwidth: 100%;\n}\n+#kc-attempted-username{\n+ font-size: 20px;\n+ font-family:inherit;\n+ font-weight: normal;\n+ padding-right:10px;\n+}\n+\n+#kc-username{\n+ text-align: center;\n+}\n+\n/* #kc-content-wrapper {\noverflow-y: hidden;\n} */\n@@ -216,6 +227,47 @@ ul#kc-totp-supported-apps {\nmargin-top: 0;\n}\n+.kc-login-tooltip{\n+ position:relative;\n+ display: inline-block;\n+}\n+\n+.kc-login-tooltip .kc-tooltip-text{\n+ top:-3px;\n+ left:160%;\n+ background-color: black;\n+ visibility: hidden;\n+ color: #fff;\n+\n+ min-width:130px;\n+ text-align: center;\n+ border-radius: 2px;\n+ box-shadow:0 1px 8px rgba(0,0,0,0.6);\n+ padding: 5px;\n+\n+ position: absolute;\n+ opacity:0;\n+ transition:opacity 0.5s;\n+}\n+\n+/* Show tooltip */\n+.kc-login-tooltip:hover .kc-tooltip-text {\n+ visibility: visible;\n+ opacity:0.7;\n+}\n+\n+/* Arrow for tooltip */\n+.kc-login-tooltip .kc-tooltip-text::after {\n+ content: \" \";\n+ position: absolute;\n+ top: 15px;\n+ right: 100%;\n+ margin-top: -5px;\n+ border-width: 5px;\n+ border-style: solid;\n+ border-color: transparent black transparent transparent;\n+}\n+\n.zocial,\na.zocial {\nwidth: 100%;\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak/login/theme.properties", "new_path": "themes/src/main/resources/theme/keycloak/login/theme.properties", "diff": "@@ -35,6 +35,7 @@ kcFeedbackWarningIcon=pficon pficon-warning-triangle-o\nkcFeedbackSuccessIcon=pficon pficon-ok\nkcFeedbackInfoIcon=pficon pficon-info\n+kcResetFlowIcon=pficon pficon-arrow fa-2x\nkcFormClass=form-horizontal\nkcFormGroupClass=form-group\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[KEYCLOAK-12426] Add username to the login form + ability to reset login
339,579
17.01.2020 10:10:16
-3,600
648c6f811ce9c3f1b4b90a1ff3bbbafd5b212a99
add null checks for migration tasks to check wether the clients to migrate are available
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_0.java", "new_path": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_0.java", "diff": "@@ -62,18 +62,22 @@ public class MigrateTo8_0_0 implements Migration {\nprotected void migrateRealmCommon(RealmModel realm) {\nClientModel adminConsoleClient = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);\n+ if (adminConsoleClient != null) {\nadminConsoleClient.setRootUrl(Constants.AUTH_ADMIN_URL_PROP);\nString adminConsoleBaseUrl = \"/admin/\" + realm.getName() + \"/console/\";\nadminConsoleClient.setBaseUrl(adminConsoleBaseUrl);\nadminConsoleClient.setRedirectUris(Collections.singleton(adminConsoleBaseUrl + \"*\"));\nadminConsoleClient.setWebOrigins(Collections.singleton(\"+\"));\n+ }\nClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);\n+ if (accountClient != null) {\naccountClient.setRootUrl(Constants.AUTH_BASE_URL_PROP);\nString accountClientBaseUrl = \"/realms/\" + realm.getName() + \"/account/\";\naccountClient.setBaseUrl(accountClientBaseUrl);\naccountClient.setRedirectUris(Collections.singleton(accountClientBaseUrl + \"*\"));\n}\n+ }\nprotected void migrateRealmMFA(KeycloakSession session, RealmModel realm, boolean jsn) {\nfor (AuthenticationFlowModel authFlow : realm.getAuthenticationFlows()) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12705 add null checks for migration tasks to check wether the clients to migrate are available (#6666)
339,364
09.01.2020 11:49:20
-3,600
475ec6f3e416247355916196b3e2181ace1c22ce
Add tests for 'Always Display in Console'
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/console/page/fragment/OnOffSwitch.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/console/page/fragment/OnOffSwitch.java", "diff": "@@ -20,6 +20,8 @@ import org.jboss.arquillian.graphene.fragment.Root;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.support.FindBy;\n+import static org.keycloak.testsuite.util.UIUtils.isElementVisible;\n+\n/**\n*\n* @author Petr Mensik\n@@ -66,4 +68,8 @@ public class OnOffSwitch {\n}\n}\n+ public boolean isVisible() {\n+ return isElementVisible(labelTag);\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/console/pom.xml", "new_path": "testsuite/integration-arquillian/tests/other/console/pom.xml", "diff": "<configuration>\n<systemProperties>\n<keycloak.theme.dir>${keycloak.theme.dir}</keycloak.theme.dir>\n- <keycloak.profile.feature.account2>enabled</keycloak.profile.feature.account2>\n</systemProperties>\n</configuration>\n</plugin>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/console/src/main/java/org/keycloak/testsuite/console/page/clients/settings/ClientSettingsForm.java", "new_path": "testsuite/integration-arquillian/tests/other/console/src/main/java/org/keycloak/testsuite/console/page/clients/settings/ClientSettingsForm.java", "diff": "@@ -157,6 +157,10 @@ public class ClientSettingsForm extends CreateClientForm {\nalwaysDisplayInConsole.setOn(enabled);\n}\n+ public boolean isAlwaysDisplayInConsoleVisible() {\n+ return alwaysDisplayInConsole.isVisible();\n+ }\n+\npublic boolean isConsentRequired() {\nreturn consentRequiredSwitch.isOn();\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/clients/ClientSettingsTest.java", "new_path": "testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/clients/ClientSettingsTest.java", "diff": "@@ -19,7 +19,9 @@ package org.keycloak.testsuite.console.clients;\nimport org.jboss.arquillian.graphene.page.Page;\nimport org.junit.Test;\n+import org.keycloak.common.Profile;\nimport org.keycloak.representations.idm.ClientRepresentation;\n+import org.keycloak.testsuite.arquillian.annotation.EnableFeature;\nimport org.keycloak.testsuite.console.page.clients.settings.ClientSettings;\nimport org.keycloak.testsuite.util.Timer;\nimport org.openqa.selenium.By;\n@@ -61,7 +63,6 @@ public class ClientSettingsTest extends AbstractClientTest {\n// update & verify\nnewClient.setClientId(\"oidc-public-updated\");\nnewClient.setName(\"updatedName\");\n- newClient.setAlwaysDisplayInConsole(true);\nList<String> redirectUris = new ArrayList<>();\nredirectUris.add(\"http://example2.test/app/*\");\n@@ -77,12 +78,13 @@ public class ClientSettingsTest extends AbstractClientTest {\nclientSettingsPage.form().setClientId(\"oidc-public-updated\");\nclientSettingsPage.form().setName(\"updatedName\");\n- clientSettingsPage.form().setAlwaysDisplayInConsole(true);\nclientSettingsPage.form().setRedirectUris(redirectUris);\nclientSettingsPage.form().setWebOrigins(webOrigins);\nclientSettingsPage.form().save();\nassertAlertSuccess();\n+ assertFalse(clientSettingsPage.form().isAlwaysDisplayInConsoleVisible());\n+\nfound = findClientByClientId(newClient.getClientId());\nassertNotNull(\"Client \" + newClient.getClientId() + \" was not found.\", found);\nassertClientSettingsEqual(newClient, found);\n@@ -94,6 +96,34 @@ public class ClientSettingsTest extends AbstractClientTest {\nassertNull(\"Deleted client \" + newClient.getClientId() + \" was found.\", found);\n}\n+ @Test\n+ @EnableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true)\n+ public void alwaysDisplayInAccountConsole() {\n+ newClient = createClientRep(\"always-display-in-console\", OIDC);\n+ createClient(newClient);\n+\n+ newClient.setRedirectUris(TEST_REDIRECT_URIs);\n+ newClient.setAlwaysDisplayInConsole(true);\n+\n+ assertFalse(clientSettingsPage.form().isAlwaysDisplayInConsole());\n+ clientSettingsPage.form().setAlwaysDisplayInConsole(true);\n+ clientSettingsPage.form().setRedirectUris(TEST_REDIRECT_URIs);\n+ clientSettingsPage.form().save();\n+ assertTrue(clientSettingsPage.form().isAlwaysDisplayInConsole());\n+\n+ ClientRepresentation found = findClientByClientId(newClient.getClientId());\n+ assertNotNull(\"Client \" + newClient.getClientId() + \" was not found.\", found);\n+ assertClientSettingsEqual(newClient, found);\n+\n+ clientSettingsPage.form().setAccessType(BEARER_ONLY);\n+ assertFalse(clientSettingsPage.form().isAlwaysDisplayInConsoleVisible());\n+ // check if the switch is displayed when change the Client to SAML and bearer-only flag is set to on (bearer-only\n+ // is not applicable for SAML but it's technically present in the Client representation and therefore can affect\n+ // the visibility of the switch)\n+ clientSettingsPage.form().setProtocol(SAML);\n+ assertTrue(clientSettingsPage.form().isAlwaysDisplayInConsoleVisible());\n+ }\n+\n@Test\npublic void createOIDCConfidential() {\nnewClient = createClientRep(\"oidc-confidetial\", OIDC);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add tests for 'Always Display in Console'
339,364
14.01.2020 09:27:31
-3,600
03306b87e8602d3b2d63ce60cb7c57746fa50efd
Introduce SameSite attribute in cookies
[ { "change_type": "MODIFY", "old_path": "adapters/oidc/js/src/main/resources/login-status-iframe.html", "new_path": "adapters/oidc/js/src/main/resources/login-status-iframe.html", "diff": "function getCookie()\n{\n- var name = 'KEYCLOAK_SESSION=';\n+ var cookie = getCookieByName('KEYCLOAK_SESSION');\n+ if (cookie === null) {\n+ return getCookieByName('KEYCLOAK_SESSION_LEGACY');\n+ }\n+ return cookie;\n+ }\n+\n+ function getCookieByName(name)\n+ {\n+ name = name + '=';\nvar ca = document.cookie.split(';');\nfor(var i=0; i<ca.length; i++)\n{\n" }, { "change_type": "MODIFY", "old_path": "adapters/spi/servlet-adapter-spi/src/main/java/org/keycloak/adapters/servlet/ServletHttpFacade.java", "new_path": "adapters/spi/servlet-adapter-spi/src/main/java/org/keycloak/adapters/servlet/ServletHttpFacade.java", "diff": "@@ -208,7 +208,7 @@ public class ServletHttpFacade implements HttpFacade {\n@Override\npublic void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly) {\nStringBuffer cookieBuf = new StringBuffer();\n- ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, null, maxAge, secure, httpOnly);\n+ ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, null, maxAge, secure, httpOnly, null);\nString cookie = cookieBuf.toString();\nresponse.addHeader(\"Set-Cookie\", cookie);\n}\n" }, { "change_type": "MODIFY", "old_path": "adapters/spi/tomcat-adapter-spi/src/main/java/org/keycloak/adapters/tomcat/CatalinaHttpFacade.java", "new_path": "adapters/spi/tomcat-adapter-spi/src/main/java/org/keycloak/adapters/tomcat/CatalinaHttpFacade.java", "diff": "@@ -219,7 +219,7 @@ public class CatalinaHttpFacade implements HttpFacade {\n@Override\npublic void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly) {\nStringBuffer cookieBuf = new StringBuffer();\n- ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, null, maxAge, secure, httpOnly);\n+ ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, null, maxAge, secure, httpOnly, null);\nString cookie = cookieBuf.toString();\nresponse.addHeader(\"Set-Cookie\", cookie);\n}\n" }, { "change_type": "MODIFY", "old_path": "common/src/main/java/org/keycloak/common/util/ServerCookie.java", "new_path": "common/src/main/java/org/keycloak/common/util/ServerCookie.java", "diff": "@@ -32,6 +32,20 @@ public class ServerCookie implements Serializable {\nprivate static final String tspecials = \",; \";\nprivate static final String tspecials2 = \"()<>@,;:\\\\\\\"/[]?={} \\t\";\n+ public enum SameSiteAttributeValue {\n+ NONE(\"None\"); // we currently support only SameSite=None; this might change in the future\n+\n+ private final String specValue;\n+ SameSiteAttributeValue(String specValue) {\n+ this.specValue = specValue;\n+ }\n+\n+ @Override\n+ public java.lang.String toString() {\n+ return specValue;\n+ }\n+ }\n+\n/*\n* Tests a string and returns true if the string counts as a\n* reserved token in the Java language.\n@@ -173,7 +187,8 @@ public class ServerCookie implements Serializable {\nString comment,\nint maxAge,\nboolean isSecure,\n- boolean httpOnly) {\n+ boolean httpOnly,\n+ SameSiteAttributeValue sameSite) {\nStringBuffer buf = new StringBuffer();\n// Servlet implementation checks name\nbuf.append(name);\n@@ -228,6 +243,12 @@ public class ServerCookie implements Serializable {\nbuf.append(path);\n}\n+ // SameSite\n+ if (sameSite != null) {\n+ buf.append(\"; SameSite=\");\n+ buf.append(sameSite.toString());\n+ }\n+\n// Secure\nif (isSecure) {\nbuf.append(\"; Secure\");\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": "@@ -96,7 +96,8 @@ import java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n-import static org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint.LOGIN_SESSION_NOTE_ADDITIONAL_REQ_PARAMS_PREFIX;\n+import static org.keycloak.common.util.ServerCookie.SameSiteAttributeValue;\n+import static org.keycloak.services.util.CookieHelper.getCookie;\n/**\n* Stateless object that manages authentication\n@@ -169,7 +170,7 @@ public class AuthenticationManager {\npublic static void expireUserSessionCookie(KeycloakSession session, UserSessionModel userSession, RealmModel realm, UriInfo uriInfo, HttpHeaders headers, ClientConnection connection) {\ntry {\n// check to see if any identity cookie is set with the same session and expire it if necessary\n- Cookie cookie = headers.getCookies().get(KEYCLOAK_IDENTITY_COOKIE);\n+ Cookie cookie = CookieHelper.getCookie(headers.getCookies(), KEYCLOAK_IDENTITY_COOKIE);\nif (cookie == null) return;\nString tokenString = cookie.getValue();\n@@ -621,7 +622,7 @@ public class AuthenticationManager {\nmaxAge = realm.getSsoSessionMaxLifespanRememberMe() > 0 ? realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan();\n}\nlogger.debugv(\"Create login cookie - name: {0}, path: {1}, max-age: {2}\", KEYCLOAK_IDENTITY_COOKIE, cookiePath, maxAge);\n- CookieHelper.addCookie(KEYCLOAK_IDENTITY_COOKIE, encoded, cookiePath, null, null, maxAge, secureOnly, true);\n+ CookieHelper.addCookie(KEYCLOAK_IDENTITY_COOKIE, encoded, cookiePath, null, null, maxAge, secureOnly, true, SameSiteAttributeValue.NONE);\n//builder.cookie(new NewCookie(cookieName, encoded, cookiePath, null, null, maxAge, secureOnly));// todo httponly , true);\nString sessionCookieValue = realm.getName() + \"/\" + user.getId();\n@@ -631,7 +632,7 @@ public class AuthenticationManager {\n// THIS SHOULD NOT BE A HTTPONLY COOKIE! It is used for OpenID Connect Iframe Session support!\n// Max age should be set to the max lifespan of the session as it's used to invalidate old-sessions on re-login\nint sessionCookieMaxAge = session.isRememberMe() && realm.getSsoSessionMaxLifespanRememberMe() > 0 ? realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan();\n- CookieHelper.addCookie(KEYCLOAK_SESSION_COOKIE, sessionCookieValue, cookiePath, null, null, sessionCookieMaxAge, secureOnly, false);\n+ CookieHelper.addCookie(KEYCLOAK_SESSION_COOKIE, sessionCookieValue, cookiePath, null, null, sessionCookieMaxAge, secureOnly, false, SameSiteAttributeValue.NONE);\nP3PHelper.addP3PHeader();\n}\n@@ -660,19 +661,19 @@ public class AuthenticationManager {\npublic static void expireIdentityCookie(RealmModel realm, UriInfo uriInfo, ClientConnection connection) {\nlogger.debug(\"Expiring identity cookie\");\nString path = getIdentityCookiePath(realm, uriInfo);\n- expireCookie(realm, KEYCLOAK_IDENTITY_COOKIE, path, true, connection);\n- expireCookie(realm, KEYCLOAK_SESSION_COOKIE, path, false, connection);\n+ expireCookie(realm, KEYCLOAK_IDENTITY_COOKIE, path, true, connection, SameSiteAttributeValue.NONE);\n+ expireCookie(realm, KEYCLOAK_SESSION_COOKIE, path, false, connection, SameSiteAttributeValue.NONE);\nString oldPath = getOldCookiePath(realm, uriInfo);\n- expireCookie(realm, KEYCLOAK_IDENTITY_COOKIE, oldPath, true, connection);\n- expireCookie(realm, KEYCLOAK_SESSION_COOKIE, oldPath, false, connection);\n+ expireCookie(realm, KEYCLOAK_IDENTITY_COOKIE, oldPath, true, connection, SameSiteAttributeValue.NONE);\n+ expireCookie(realm, KEYCLOAK_SESSION_COOKIE, oldPath, false, connection, SameSiteAttributeValue.NONE);\n}\npublic static void expireOldIdentityCookie(RealmModel realm, UriInfo uriInfo, ClientConnection connection) {\nlogger.debug(\"Expiring old identity cookie with wrong path\");\nString oldPath = getOldCookiePath(realm, uriInfo);\n- expireCookie(realm, KEYCLOAK_IDENTITY_COOKIE, oldPath, true, connection);\n- expireCookie(realm, KEYCLOAK_SESSION_COOKIE, oldPath, false, connection);\n+ expireCookie(realm, KEYCLOAK_IDENTITY_COOKIE, oldPath, true, connection, SameSiteAttributeValue.NONE);\n+ expireCookie(realm, KEYCLOAK_SESSION_COOKIE, oldPath, false, connection, SameSiteAttributeValue.NONE);\n}\n@@ -680,14 +681,14 @@ public class AuthenticationManager {\nlogger.debug(\"Expiring remember me cookie\");\nString path = getIdentityCookiePath(realm, uriInfo);\nString cookieName = KEYCLOAK_REMEMBER_ME;\n- expireCookie(realm, cookieName, path, true, connection);\n+ expireCookie(realm, cookieName, path, true, connection, null);\n}\npublic static void expireOldAuthSessionCookie(RealmModel realm, UriInfo uriInfo, ClientConnection connection) {\nlogger.debugv(\"Expire {1} cookie .\", AuthenticationSessionManager.AUTH_SESSION_ID);\nString oldPath = getOldCookiePath(realm, uriInfo);\n- expireCookie(realm, AuthenticationSessionManager.AUTH_SESSION_ID, oldPath, true, connection);\n+ expireCookie(realm, AuthenticationSessionManager.AUTH_SESSION_ID, oldPath, true, connection, null);\n}\nprotected static String getIdentityCookiePath(RealmModel realm, UriInfo uriInfo) {\n@@ -710,10 +711,10 @@ public class AuthenticationManager {\nreturn uri.getRawPath();\n}\n- public static void expireCookie(RealmModel realm, String cookieName, String path, boolean httpOnly, ClientConnection connection) {\n+ public static void expireCookie(RealmModel realm, String cookieName, String path, boolean httpOnly, ClientConnection connection, SameSiteAttributeValue sameSite) {\nlogger.debugf(\"Expiring cookie: %s path: %s\", cookieName, path);\nboolean secureOnly = realm.getSslRequired().isRequired(connection);;\n- CookieHelper.addCookie(cookieName, \"\", path, null, \"Expiring cookie\", 0, secureOnly, httpOnly);\n+ CookieHelper.addCookie(cookieName, \"\", path, null, \"Expiring cookie\", 0, secureOnly, httpOnly, sameSite);\n}\npublic AuthResult authenticateIdentityCookie(KeycloakSession session, RealmModel realm) {\n@@ -721,7 +722,7 @@ public class AuthenticationManager {\n}\npublic static AuthResult authenticateIdentityCookie(KeycloakSession session, RealmModel realm, boolean checkActive) {\n- Cookie cookie = session.getContext().getRequestHeaders().getCookies().get(KEYCLOAK_IDENTITY_COOKIE);\n+ Cookie cookie = CookieHelper.getCookie(session.getContext().getRequestHeaders().getCookies(), KEYCLOAK_IDENTITY_COOKIE);\nif (cookie == null || \"\".equals(cookie.getValue())) {\nlogger.debugv(\"Could not find cookie: {0}\", KEYCLOAK_IDENTITY_COOKIE);\nreturn null;\n@@ -756,7 +757,7 @@ public class AuthenticationManager {\nClientSessionContext clientSessionCtx,\nHttpRequest request, UriInfo uriInfo, ClientConnection clientConnection,\nEventBuilder event, AuthenticationSessionModel authSession, LoginProtocol protocol) {\n- Cookie sessionCookie = request.getHttpHeaders().getCookies().get(AuthenticationManager.KEYCLOAK_SESSION_COOKIE);\n+ Cookie sessionCookie = getCookie(request.getHttpHeaders().getCookies(), AuthenticationManager.KEYCLOAK_SESSION_COOKIE);\nif (sessionCookie != null) {\nString[] split = sessionCookie.getValue().split(\"/\");\n@@ -801,7 +802,7 @@ public class AuthenticationManager {\n}\npublic static String getSessionIdFromSessionCookie(KeycloakSession session) {\n- Cookie cookie = session.getContext().getRequestHeaders().getCookies().get(KEYCLOAK_SESSION_COOKIE);\n+ Cookie cookie = getCookie(session.getContext().getRequestHeaders().getCookies(), KEYCLOAK_SESSION_COOKIE);\nif (cookie == null || \"\".equals(cookie.getValue())) {\nlogger.debugv(\"Could not find cookie: {0}\", KEYCLOAK_SESSION_COOKIE);\nreturn null;\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java", "new_path": "testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java", "diff": "@@ -58,6 +58,7 @@ import org.keycloak.representations.idm.UserRepresentation;\nimport org.keycloak.services.managers.AuthenticationManager;\nimport org.keycloak.services.resource.RealmResourceProvider;\nimport org.keycloak.services.scheduled.ClearExpiredUserSessions;\n+import org.keycloak.services.util.CookieHelper;\nimport org.keycloak.storage.UserStorageProvider;\nimport org.keycloak.testsuite.components.TestProvider;\nimport org.keycloak.testsuite.components.TestProviderFactory;\n@@ -559,7 +560,7 @@ public class TestingResourceProvider implements RealmResourceProvider {\n@Produces(MediaType.APPLICATION_JSON)\npublic String getSSOCookieValue() {\nMap<String, Cookie> cookies = request.getHttpHeaders().getCookies();\n- Cookie cookie = cookies.get(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE);\n+ Cookie cookie = CookieHelper.getCookie(cookies, AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE);\nif (cookie == null) return null;\nreturn cookie.getValue();\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/resources/org/keycloak/testsuite/integration-arquillian-testsuite-providers/main/module.xml", "new_path": "testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/resources/org/keycloak/testsuite/integration-arquillian-testsuite-providers/main/module.xml", "diff": "<module name=\"org.hibernate\"/>\n<module name=\"org.javassist\"/>\n<module name=\"org.jboss.modules\"/>\n+ <module name=\"org.apache.httpcomponents.core\"/>\n</dependencies>\n</module>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/updaters/ClientAttributeUpdater.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/updaters/ClientAttributeUpdater.java", "diff": "@@ -74,6 +74,11 @@ public class ClientAttributeUpdater extends ServerResourceUpdater<ClientAttribut\nreturn this;\n}\n+ public ClientAttributeUpdater setRedirectUris(List<String> values) {\n+ this.rep.setRedirectUris(values);\n+ return this;\n+ }\n+\npublic ClientAttributeUpdater removeAttribute(String name) {\nthis.rep.getAttributes().remove(name);\nreturn this;\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": "@@ -50,6 +50,11 @@ public class JSObjectBuilder {\nreturn this;\n}\n+ public JSObjectBuilder disableCheckLoginIframe() {\n+ arguments.put(\"checkLoginIframe\", false);\n+ return this;\n+ }\n+\npublic JSObjectBuilder loginRequiredOnLoad() {\narguments.put(\"onLoad\", \"login-required\");\nreturn this;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLSameSiteTest.java", "diff": "+package org.keycloak.testsuite.adapter.servlet;\n+\n+import org.jboss.arquillian.container.test.api.Deployment;\n+import org.jboss.arquillian.graphene.page.Page;\n+import org.jboss.shrinkwrap.api.spec.WebArchive;\n+import org.junit.Test;\n+import org.keycloak.adapters.rotation.PublicKeyLocator;\n+import org.keycloak.testsuite.adapter.filter.AdapterActionsFilter;\n+import org.keycloak.testsuite.adapter.page.Employee2Servlet;\n+import org.keycloak.testsuite.adapter.page.EmployeeSigServlet;\n+import org.keycloak.testsuite.arquillian.annotation.AppServerContainer;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.updaters.ClientAttributeUpdater;\n+import org.keycloak.testsuite.utils.arquillian.ContainerConstants;\n+import org.openqa.selenium.By;\n+\n+import javax.ws.rs.core.UriBuilder;\n+import java.io.IOException;\n+import java.net.URISyntaxException;\n+import java.util.Collections;\n+\n+import static org.keycloak.testsuite.arquillian.AppServerTestEnricher.getAppServerContextRoot;\n+import static org.keycloak.testsuite.auth.page.AuthRealm.SAMLSERVLETDEMO;\n+import static org.keycloak.testsuite.saml.AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2;\n+import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;\n+import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad;\n+import static org.keycloak.testsuite.util.WaitUtils.waitUntilElement;\n+\n+/**\n+ * @author mhajas\n+ */\n+@AppServerContainer(ContainerConstants.APP_SERVER_UNDERTOW)\n+@AppServerContainer(ContainerConstants.APP_SERVER_WILDFLY)\n+@AppServerContainer(ContainerConstants.APP_SERVER_WILDFLY_DEPRECATED)\n+@AppServerContainer(ContainerConstants.APP_SERVER_EAP)\n+@AppServerContainer(ContainerConstants.APP_SERVER_EAP6)\n+@AppServerContainer(ContainerConstants.APP_SERVER_EAP71)\n+@AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT7)\n+@AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT8)\n+@AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT9)\n+@AuthServerContainerExclude(AuthServerContainerExclude.AuthServer.REMOTE)\n+public class SAMLSameSiteTest extends AbstractSAMLServletAdapterTest {\n+ private static final String NIP_IO_URL = \"app-saml-127-0-0-1.nip.io\";\n+ private static final String NIP_IO_EMPLOYEE2_URL = getAppServerContextRoot().replace(\"localhost\", NIP_IO_URL) + \"/employee2/\";\n+\n+ @Deployment(name = Employee2Servlet.DEPLOYMENT_NAME)\n+ protected static WebArchive employee2() {\n+ return samlServletDeployment(Employee2Servlet.DEPLOYMENT_NAME, WEB_XML_WITH_ACTION_FILTER, SendUsernameServlet.class, AdapterActionsFilter.class, PublicKeyLocator.class);\n+ }\n+\n+ @Page\n+ protected Employee2Servlet employee2ServletPage;\n+\n+ @Test\n+ public void samlWorksWithSameSiteCookieTest() throws URISyntaxException {\n+ getCleanup(SAMLSERVLETDEMO).addCleanup(ClientAttributeUpdater.forClient(adminClient, SAMLSERVLETDEMO, SAML_CLIENT_ID_EMPLOYEE_2)\n+ .setRedirectUris(Collections.singletonList(NIP_IO_EMPLOYEE2_URL + \"*\"))\n+ .setAdminUrl(NIP_IO_EMPLOYEE2_URL + \"saml\")\n+ .update());\n+\n+ // Navigate to url with nip.io to trick browser the adapter lives on different domain\n+ driver.navigate().to(NIP_IO_EMPLOYEE2_URL);\n+ assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);\n+\n+ // Login and check the user is successfully logged in\n+ testRealmSAMLPostLoginPage.form().login(bburkeUser);\n+ waitUntilElement(By.xpath(\"//body\")).text().contains(\"[email protected]\");\n+\n+ // Logout\n+ driver.navigate().to(UriBuilder.fromUri(NIP_IO_EMPLOYEE2_URL).queryParam(\"GLO\", \"true\").build().toASCIIString());\n+ waitForPageToLoad();\n+\n+ // Check logged out\n+ driver.navigate().to(NIP_IO_EMPLOYEE2_URL);\n+ assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java", "diff": "package org.keycloak.testsuite.admin;\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.methods.HttpUriRequest;\n+import org.apache.http.client.methods.RequestBuilder;\n+import org.apache.http.impl.client.BasicCookieStore;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.impl.client.HttpClientBuilder;\n+import org.apache.http.util.EntityUtils;\nimport org.jboss.arquillian.graphene.page.Page;\nimport org.jboss.resteasy.client.jaxrs.ResteasyClient;\nimport org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;\n@@ -49,6 +56,8 @@ import org.keycloak.services.managers.AuthenticationManager;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.AssertEvents;\nimport org.keycloak.testsuite.arquillian.AuthServerTestEnricher;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\nimport org.keycloak.testsuite.auth.page.AuthRealm;\nimport org.keycloak.testsuite.pages.AppPage;\nimport org.keycloak.testsuite.pages.LoginPage;\n@@ -61,18 +70,16 @@ import org.keycloak.testsuite.util.UserBuilder;\nimport org.openqa.selenium.Cookie;\nimport javax.ws.rs.ClientErrorException;\n-import javax.ws.rs.client.Client;\nimport javax.ws.rs.core.HttpHeaders;\n-import javax.ws.rs.core.NewCookie;\nimport javax.ws.rs.core.Response;\n+import java.io.IOException;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport static org.hamcrest.Matchers.containsString;\n-import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n-import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\n+import static org.keycloak.testsuite.util.OAuthClient.AUTH_SERVER_ROOT;\n/**\n* Tests Undertow Adapter\n@@ -238,21 +245,19 @@ public class ImpersonationTest extends AbstractKeycloakTest {\n}\nprivate Cookie impersonate(Keycloak adminClient, String admin, String adminRealm) {\n- Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();\n+ BasicCookieStore cookieStore = new BasicCookieStore();\n+ try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build()) {\n- try (Response response = httpClient.target(OAuthClient.AUTH_SERVER_ROOT)\n- .path(\"admin\")\n- .path(\"realms\")\n- .path(\"test\")\n- .path(\"users/\" + impersonatedUserId + \"/impersonation\")\n- .request()\n- .header(HttpHeaders.AUTHORIZATION, \"Bearer \" + adminClient.tokenManager().getAccessTokenString())\n- .post(null)) {\n+ HttpUriRequest req = RequestBuilder.post()\n+ .setUri(AUTH_SERVER_ROOT + \"/admin/realms/test/users/\" + impersonatedUserId + \"/impersonation\")\n+ .addHeader(HttpHeaders.AUTHORIZATION, \"Bearer \" + adminClient.tokenManager().getAccessTokenString())\n+ .build();\n- Map data = response.readEntity(Map.class);\n+ HttpResponse res = httpClient.execute(req);\n+ String resBody = EntityUtils.toString(res.getEntity());\n- Assert.assertNotNull(data);\n- Assert.assertNotNull(data.get(\"redirect\"));\n+ Assert.assertNotNull(resBody);\n+ Assert.assertTrue(resBody.contains(\"redirect\"));\nevents.expect(EventType.IMPERSONATE)\n.session(AssertEvents.isUUID())\n@@ -275,10 +280,15 @@ public class ImpersonationTest extends AbstractKeycloakTest {\nAssert.assertNotNull(notes.get(ImpersonationSessionNote.IMPERSONATOR_ID.toString()));\nAssert.assertEquals(admin, notes.get(ImpersonationSessionNote.IMPERSONATOR_USERNAME.toString()));\n- NewCookie cookie = response.getCookies().get(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE);\n+ org.apache.http.cookie.Cookie cookie = cookieStore.getCookies().stream()\n+ .filter(c -> c.getName().equals(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE))\n+ .findAny().orElse(null);\nAssert.assertNotNull(cookie);\n- return new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiry(), cookie.isSecure(), cookie.isHttpOnly());\n+ return new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiryDate(), cookie.isSecure(), true);\n+ }\n+ catch (IOException e) {\n+ throw new RuntimeException(e);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java", "diff": "*/\npackage org.keycloak.testsuite.cookies;\n-import org.keycloak.representations.idm.RealmRepresentation;\n-import org.keycloak.services.managers.AuthenticationManager;\n-import org.keycloak.testsuite.AbstractKeycloakTest;\n-import org.keycloak.testsuite.auth.page.AuthRealm;\n-import org.keycloak.testsuite.pages.LoginPage;\n-import org.keycloak.testsuite.util.OAuthClient;\n-import org.keycloak.testsuite.util.OAuthClient.AuthorizationEndpointResponse;\n-import org.keycloak.testsuite.util.RealmBuilder;\n-import java.util.List;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.protocol.HttpClientContext;\n@@ -36,14 +27,34 @@ import org.apache.http.protocol.HttpContext;\nimport org.apache.http.util.EntityUtils;\nimport org.jboss.arquillian.graphene.page.Page;\nimport org.junit.Test;\n+import org.keycloak.representations.idm.RealmRepresentation;\n+import org.keycloak.testsuite.AbstractKeycloakTest;\n+import org.keycloak.testsuite.auth.page.AuthRealm;\n+import org.keycloak.testsuite.pages.LoginPage;\n+import org.keycloak.testsuite.util.OAuthClient;\n+import org.keycloak.testsuite.util.OAuthClient.AuthorizationEndpointResponse;\n+import org.keycloak.testsuite.util.RealmBuilder;\n+import org.openqa.selenium.Cookie;\n+\n+import java.util.List;\n+\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.not;\n+import static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertFalse;\n+import static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertThat;\n+import static org.junit.Assert.assertTrue;\n+import static org.keycloak.services.managers.AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE;\n+import static org.keycloak.services.managers.AuthenticationManager.KEYCLOAK_SESSION_COOKIE;\n+import static org.keycloak.services.util.CookieHelper.LEGACY_COOKIE;\nimport static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;\n+import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWithLoginUrlOf;\n/**\n*\n* @author hmlnarik\n+ * @author Vaclav Muzikar <[email protected]>\n*/\npublic class CookieTest extends AbstractKeycloakTest {\n@@ -58,10 +69,23 @@ public class CookieTest extends AbstractKeycloakTest {\ntestRealms.add(testRealm);\n}\n+ @Override\n+ public void setDefaultPageUriParameters() {\n+ super.setDefaultPageUriParameters();\n+ accountPage.setAuthRealm(AuthRealm.TEST);\n+ }\n+\n@Test\npublic void testCookieValue() throws Exception {\n- accountPage.setAuthRealm(AuthRealm.TEST);\n+ testCookieValue(KEYCLOAK_IDENTITY_COOKIE);\n+ }\n+ @Test\n+ public void testLegacyCookieValue() throws Exception {\n+ testCookieValue(KEYCLOAK_IDENTITY_COOKIE + LEGACY_COOKIE);\n+ }\n+\n+ private void testCookieValue(String cookieName) throws Exception {\nfinal String accountClientId = realmsResouce().realm(\"test\").clients().findByClientId(\"account\").get(0).getId();\nfinal String clientSecret = realmsResouce().realm(\"test\").clients().get(accountClientId).getSecret().getValue();\n@@ -74,7 +98,7 @@ public class CookieTest extends AbstractKeycloakTest {\ntry (CloseableHttpClient hc = OAuthClient.newCloseableHttpClient()) {\nBasicCookieStore cookieStore = new BasicCookieStore();\n- BasicClientCookie cookie = new BasicClientCookie(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE, accessToken);\n+ BasicClientCookie cookie = new BasicClientCookie(cookieName, accessToken);\ncookie.setDomain(\"localhost\");\ncookie.setPath(\"/\");\ncookieStore.addCookie(cookie);\n@@ -99,8 +123,6 @@ public class CookieTest extends AbstractKeycloakTest {\n@Test\npublic void testCookieValueLoggedOut() throws Exception {\n- accountPage.setAuthRealm(AuthRealm.TEST);\n-\nfinal String accountClientId = realmsResouce().realm(\"test\").clients().findByClientId(\"account\").get(0).getId();\nfinal String clientSecret = realmsResouce().realm(\"test\").clients().get(accountClientId).getSecret().getValue();\n@@ -114,7 +136,7 @@ public class CookieTest extends AbstractKeycloakTest {\ntry (CloseableHttpClient hc = OAuthClient.newCloseableHttpClient()) {\nBasicCookieStore cookieStore = new BasicCookieStore();\n- BasicClientCookie cookie = new BasicClientCookie(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE, accessToken);\n+ BasicClientCookie cookie = new BasicClientCookie(KEYCLOAK_IDENTITY_COOKIE, accessToken);\ncookie.setDomain(\"localhost\");\ncookie.setPath(\"/\");\ncookieStore.addCookie(cookie);\n@@ -137,4 +159,34 @@ public class CookieTest extends AbstractKeycloakTest {\n}\n}\n+ @Test\n+ public void legacyCookiesTest() {\n+ accountPage.navigateTo();\n+ assertCurrentUrlStartsWithLoginUrlOf(accountPage);\n+\n+ loginPage.login(\"test-user@localhost\", \"password\");\n+\n+ Cookie sameSiteIdentityCookie = driver.manage().getCookieNamed(KEYCLOAK_IDENTITY_COOKIE);\n+ Cookie legacyIdentityCookie = driver.manage().getCookieNamed(KEYCLOAK_IDENTITY_COOKIE + LEGACY_COOKIE);\n+ Cookie sameSiteSessionCookie = driver.manage().getCookieNamed(KEYCLOAK_SESSION_COOKIE);\n+ Cookie legacySessionCookie = driver.manage().getCookieNamed(KEYCLOAK_SESSION_COOKIE + LEGACY_COOKIE);\n+\n+ assertSameSiteCookies(sameSiteIdentityCookie, legacyIdentityCookie);\n+ assertSameSiteCookies(sameSiteSessionCookie, legacySessionCookie);\n+ }\n+\n+ private void assertSameSiteCookies(Cookie sameSiteCookie, Cookie legacyCookie) {\n+ assertNotNull(\"SameSite cookie shouldn't be null\", sameSiteCookie);\n+ assertNotNull(\"Legacy cookie shouldn't be null\", legacyCookie);\n+\n+ assertEquals(sameSiteCookie.getValue(), legacyCookie.getValue());\n+ assertEquals(sameSiteCookie.getDomain(), legacyCookie.getDomain());\n+ assertEquals(sameSiteCookie.getPath(), legacyCookie.getPath());\n+ assertEquals(sameSiteCookie.getExpiry(), legacyCookie.getExpiry());\n+ assertTrue(\"SameSite cookie should always have Secure attribute\", sameSiteCookie.isSecure());\n+ assertFalse(\"Legacy cookie shouldn't have Secure attribute\", legacyCookie.isSecure()); // this relies on test realm config\n+ assertEquals(sameSiteCookie.isHttpOnly(), legacyCookie.isHttpOnly());\n+ // WebDriver currently doesn't support SameSite attribute therefore we cannot check it's present in the cookie\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/javascript/AbstractJavascriptTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/javascript/AbstractJavascriptTest.java", "diff": "@@ -45,6 +45,7 @@ public abstract class AbstractJavascriptTest extends AbstractAuthTest {\nvoid apply(T a, U b, V c, W d);\n}\n+ public static final String NIP_IO_URL = \"js-app-127-0-0-1.nip.io\";\npublic static final String CLIENT_ID = \"js-console\";\npublic static final String REALM_NAME = \"test\";\npublic static final String SPACE_REALM_NAME = \"Example realm\";\n@@ -112,7 +113,8 @@ public abstract class AbstractJavascriptTest extends AbstractAuthTest {\n.client(\nClientBuilder.create()\n.clientId(CLIENT_ID)\n- .redirectUris(oauth.SERVER_ROOT + JAVASCRIPT_URL + \"/*\", oauth.SERVER_ROOT + JAVASCRIPT_ENCODED_SPACE_URL + \"/*\")\n+ .redirectUris(oauth.SERVER_ROOT.replace(\"localhost\", NIP_IO_URL) + JAVASCRIPT_URL + \"/*\", oauth.SERVER_ROOT + JAVASCRIPT_ENCODED_SPACE_URL + \"/*\")\n+ .addWebOrigin(oauth.SERVER_ROOT.replace(\"localhost\", NIP_IO_URL))\n.publicClient()\n)\n.accessTokenLifespan(30 + TOKEN_LIFESPAN_LEEWAY)\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": "@@ -38,6 +38,7 @@ import java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static java.lang.Math.toIntExact;\n+import static org.hamcrest.CoreMatchers.anyOf;\nimport static org.hamcrest.CoreMatchers.both;\nimport static org.hamcrest.CoreMatchers.containsString;\nimport static org.hamcrest.Matchers.greaterThan;\n@@ -83,12 +84,17 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\n@Before\npublic void setDefaultEnvironment() {\n- testAppUrl = authServerContextRootPage + JAVASCRIPT_URL + \"/index.html\";\n+ testAppUrl = authServerContextRootPage.toString().replace(\"localhost\", NIP_IO_URL) + JAVASCRIPT_URL + \"/index.html\";\njsDriverTestRealmLoginPage.setAuthRealm(REALM_NAME);\noAuthGrantPage.setAuthRealm(REALM_NAME);\napplicationsPage.setAuthRealm(REALM_NAME);\n+ jsDriver.navigate().to(oauth.getLoginFormUrl());\n+ waitForPageToLoad();\n+ events.poll();\n+ jsDriver.manage().deleteAllCookies();\n+\njsDriver.navigate().to(testAppUrl);\nwaitUntilElement(outputArea).is().present();\n@@ -141,8 +147,15 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\n.login(this::assertOnLoginPage)\n.loginForm(testUser, this::assertOnTestAppUrl)\n.init(defaultArguments(), this::assertSuccessfullyLoggedIn)\n+ .logout(this::assertOnTestAppUrl)\n+\n+ .init(defaultArguments(), this::assertInitNotAuth)\n.login(\"{kcLocale: 'de'}\", assertLocaleIsSet(\"de\"))\n+ .loginForm(testUser, this::assertOnTestAppUrl)\n.init(defaultArguments(), this::assertSuccessfullyLoggedIn)\n+ .logout(this::assertOnTestAppUrl)\n+\n+ .init(defaultArguments(), this::assertInitNotAuth)\n.login(\"{kcLocale: 'en'}\", assertLocaleIsSet(\"en\"));\n}\n@@ -166,7 +179,7 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\n.init(checkSSO, this::assertSuccessfullyLoggedIn)\n.refresh()\n.init(checkSSO\n- .add(\"silentCheckSsoRedirectUri\", authServerContextRootPage + JAVASCRIPT_URL + \"/silent-check-sso.html\")\n+ .add(\"silentCheckSsoRedirectUri\", authServerContextRootPage.toString().replace(\"localhost\", NIP_IO_URL) + JAVASCRIPT_URL + \"/silent-check-sso.html\")\n, this::assertSuccessfullyLoggedIn);\n}\n@@ -179,8 +192,8 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\n.init(checkSSO, this::assertSuccessfullyLoggedIn)\n.refresh()\n.init(checkSSO\n- .add(\"checkLoginIframe\", false)\n- .add(\"silentCheckSsoRedirectUri\", authServerContextRootPage + JAVASCRIPT_URL + \"/silent-check-sso.html\")\n+ .disableCheckLoginIframe()\n+ .add(\"silentCheckSsoRedirectUri\", authServerContextRootPage.toString().replace(\"localhost\", NIP_IO_URL) + JAVASCRIPT_URL + \"/silent-check-sso.html\")\n, this::assertSuccessfullyLoggedIn);\n}\n@@ -205,7 +218,7 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\nJSObjectBuilder checkSSO = defaultArguments().checkSSOOnLoad();\ntestExecutor.init(checkSSO\n.add(\"checkLoginIframe\", false)\n- .add(\"silentCheckSsoRedirectUri\", authServerContextRootPage + JAVASCRIPT_URL + \"/silent-check-sso.html\")\n+ .add(\"silentCheckSsoRedirectUri\", authServerContextRootPage.toString().replace(\"localhost\", NIP_IO_URL) + JAVASCRIPT_URL + \"/silent-check-sso.html\")\n, this::assertInitNotAuth);\n}\n@@ -378,7 +391,8 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\n.addHeader(\"Authorization\", \"Bearer ' + keycloak.token + '\");\ntestExecutor.init(defaultArguments())\n- .sendXMLHttpRequest(request, assertResponseStatus(401))\n+ // Possibility of 0 and 401 is caused by this issue: https://issues.redhat.com/browse/KEYCLOAK-12686\n+ .sendXMLHttpRequest(request, response -> assertThat(response, hasEntry(is(\"status\"), anyOf(is(0L), is(401L)))))\n.refresh();\nif (!\"phantomjs\".equals(System.getProperty(\"js.browser\"))) {\n// I have no idea why, but this request doesn't work with phantomjs, it works in chrome\n@@ -422,7 +436,8 @@ public class JavascriptAdapterTest extends AbstractJavascriptTest {\nsetTimeOffset(67);\ntestExecutor.addTimeSkew(-34)\n- .sendXMLHttpRequest(request, assertResponseStatus(401))\n+ // Possibility of 0 and 401 is caused by this issue: https://issues.redhat.com/browse/KEYCLOAK-12686\n+ .sendXMLHttpRequest(request, response -> assertThat(response, hasEntry(is(\"status\"), anyOf(is(0L), is(401L)))))\n.refreshToken(5, assertEventsContains(\"Auth Refresh Success\"))\n.sendXMLHttpRequest(request, assertResponseStatus(200));\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12125 Introduce SameSite attribute in cookies Co-authored-by: mhajas <[email protected]> Co-authored-by: Peter Skopek <[email protected]>
339,332
10.01.2020 14:54:21
-3,600
632925cc065c1206dc88c4f44ef94d229de0b39b
[i18n nl] Updated totpStep1 - removed a-href tags A tags are not rendered as-is - they are escaped. This fixes html output as plaintext in the dutch translation.
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources-community/theme/base/account/messages/messages_nl.properties", "new_path": "themes/src/main/resources-community/theme/base/account/messages/messages_nl.properties", "diff": "@@ -88,7 +88,7 @@ offlineToken=Offline Token\nrevoke=Vergunning intrekken\nconfigureAuthenticators=Ingestelde authenticators\nmobile=Mobiel nummer\n-totpStep1=Installeer <a href=\"https://freeotp.github.io/\" target=\"_blank\">FreeOTP</a> of Google Authenticator op uw apparaat. Beide toepassingen zijn beschikbaar in <a href=\"https://play.google.com\">Google Play</a> en de Apple App Store.\n+totpStep1=Installeer een van de onderstaande applicaties op Uw mobiele apparaat\ntotpStep2=Open de toepassing en scan de QR-code of voer de sleutel in.\ntotpStep3=Voer de door de toepassing gegeven eenmalige code in en klik op Opslaan om de configuratie af te ronden.\nmissingUsernameMessage=Gebruikersnaam ontbreekt.\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[i18n nl] Updated totpStep1 - removed a-href tags A tags are not rendered as-is - they are escaped. This fixes html output as plaintext in the dutch translation.
339,332
18.01.2020 19:44:31
-3,600
910324e4eb87bfec9fb9a6ac14a9ba13d90f350f
minor changes (punctuation, caps)
[ { "change_type": "MODIFY", "old_path": "themes/src/main/resources-community/theme/base/account/messages/messages_nl.properties", "new_path": "themes/src/main/resources-community/theme/base/account/messages/messages_nl.properties", "diff": "@@ -88,7 +88,7 @@ offlineToken=Offline Token\nrevoke=Vergunning intrekken\nconfigureAuthenticators=Ingestelde authenticators\nmobile=Mobiel nummer\n-totpStep1=Installeer een van de onderstaande applicaties op Uw mobiele apparaat\n+totpStep1=Installeer een van de onderstaande applicaties op uw mobiele apparaat:\ntotpStep2=Open de toepassing en scan de QR-code of voer de sleutel in.\ntotpStep3=Voer de door de toepassing gegeven eenmalige code in en klik op Opslaan om de configuratie af te ronden.\nmissingUsernameMessage=Gebruikersnaam ontbreekt.\n" } ]
Java
Apache License 2.0
keycloak/keycloak
minor changes (punctuation, caps)
339,581
21.01.2020 19:43:25
-3,600
36eba64f07403bb97fe7cb57eb356b5154e7096f
Performance degradation after upgrade to Keycloak 8
[ { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java", "new_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java", "diff": "@@ -1232,9 +1232,10 @@ public class RealmAdapter implements CachedRealmModel {\nreturn cached.getExecutionsById().get(id);\n}\n+ @Override\npublic AuthenticationExecutionModel getAuthenticationExecutionByFlowId(String flowId) {\n- getDelegateForUpdate();\n- return updated.getAuthenticationExecutionByFlowId(flowId);\n+ if (isUpdated()) return updated.getAuthenticationExecutionByFlowId(flowId);\n+ return cached.getAuthenticationExecutionByFlowId(flowId);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java", "new_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java", "diff": "@@ -120,6 +120,7 @@ public class CachedRealm extends AbstractExtendableRevisioned {\nprotected Map<String, RequiredActionProviderModel> requiredActionProvidersByAlias = new HashMap<>();\nprotected MultivaluedHashMap<String, AuthenticationExecutionModel> authenticationExecutions = new MultivaluedHashMap<>();\nprotected Map<String, AuthenticationExecutionModel> executionsById = new HashMap<>();\n+ protected Map<String, AuthenticationExecutionModel> executionsByFlowId = new HashMap<>();\nprotected AuthenticationFlowModel browserFlow;\nprotected AuthenticationFlowModel registrationFlow;\n@@ -256,6 +257,9 @@ public class CachedRealm extends AbstractExtendableRevisioned {\nfor (AuthenticationExecutionModel execution : model.getAuthenticationExecutions(flow.getId())) {\nauthenticationExecutions.add(flow.getId(), execution);\nexecutionsById.put(execution.getId(), execution);\n+ if (execution.getFlowId() != null) {\n+ executionsByFlowId.put(execution.getFlowId(), execution);\n+ }\n}\n}\n@@ -585,6 +589,10 @@ public class CachedRealm extends AbstractExtendableRevisioned {\nreturn authenticationExecutions;\n}\n+ public AuthenticationExecutionModel getAuthenticationExecutionByFlowId(String flowId) {\n+ return executionsByFlowId.get(flowId);\n+ }\n+\npublic Map<String, AuthenticationExecutionModel> getExecutionsById() {\nreturn executionsById;\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12674 Performance degradation after upgrade to Keycloak 8 (#6685)
339,414
22.01.2020 12:26:28
-3,600
8d312d748baee6d8bc51863b045998a0b59f0978
Old account console: UI not updated after removing of TOTP
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserCredentialStore.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserCredentialStore.java", "diff": "@@ -175,6 +175,7 @@ public class JpaUserCredentialStore implements UserCredentialStore {\n}\nem.remove(entity);\n+ em.flush();\nreturn entity;\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": "@@ -918,17 +918,7 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {\nAssert.assertEquals(\"Your account has been updated.\", profilePage.getSuccess());\n}\n- @Test\n- public void setupTotp() {\n- totpPage.open();\n- loginPage.login(\"test-user@localhost\", \"password\");\n-\n- events.expectLogin().client(\"account\").detail(Details.REDIRECT_URI, getAccountRedirectUrl() + \"?path=totp\").assertEvent();\n-\n- Assert.assertTrue(totpPage.isCurrent());\n-\n- assertFalse(driver.getPageSource().contains(\"Remove Google\"));\n-\n+ public void totpPageSetup() {\nString pageSource = driver.getPageSource();\nassertTrue(pageSource.contains(\"Install one of the following applications on your mobile\"));\n@@ -940,10 +930,10 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {\nassertTrue(pageSource.contains(\"Unable to scan?\"));\nassertFalse(pageSource.contains(\"Scan barcode?\"));\n+ }\n- totpPage.clickManual();\n-\n- pageSource = driver.getPageSource();\n+ public void totpPageSetupManual() {\n+ String pageSource = driver.getPageSource();\nassertTrue(pageSource.contains(\"Install one of the following applications on your mobile\"));\nassertTrue(pageSource.contains(\"FreeOTP\"));\n@@ -954,6 +944,22 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {\nassertFalse(pageSource.contains(\"Unable to scan?\"));\nassertTrue(pageSource.contains(\"Scan barcode?\"));\n+ }\n+\n+ @Test\n+ public void setupTotp() {\n+ totpPage.open();\n+ loginPage.login(\"test-user@localhost\", \"password\");\n+\n+ events.expectLogin().client(\"account\").detail(Details.REDIRECT_URI, getAccountRedirectUrl() + \"?path=totp\").assertEvent();\n+\n+ Assert.assertTrue(totpPage.isCurrent());\n+\n+ assertFalse(driver.getPageSource().contains(\"Remove Google\"));\n+\n+ totpPageSetup();\n+\n+ totpPage.clickManual();\nassertTrue(UIUtils.getTextFromElement(driver.findElement(By.id(\"kc-totp-secret-key\"))).matches(\"[\\\\w]{4}( [\\\\w]{4}){7}\"));\n@@ -978,6 +984,8 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {\ntotpPage.removeTotp();\nevents.expectAccount(EventType.REMOVE_TOTP).assertEvent();\n+ // KEYCLOAK-12163\n+ totpPageSetupManual();\naccountPage.logOut();\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12163 Old account console: UI not updated after removing of TOTP (#6688)
339,281
20.01.2020 18:55:44
-3,600
47d6d65bbb18a5f23a5b67c2282e2090fab9e4a3
workaround hibernate bug - set explicitly dialect for oracle version greater than 12
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/connections/jpa/DefaultJpaConnectionProviderFactory.java", "new_path": "model/jpa/src/main/java/org/keycloak/connections/jpa/DefaultJpaConnectionProviderFactory.java", "diff": "@@ -276,6 +276,11 @@ public class DefaultJpaConnectionProviderFactory implements JpaConnectionProvide\nreturn sql2012Dialect;\n}\n}\n+ // For Oracle19c, we may need to set dialect explicitly to workaround https://hibernate.atlassian.net/browse/HHH-13184\n+ if (dbProductName.equals(\"Oracle\") && connection.getMetaData().getDatabaseMajorVersion() > 12) {\n+ logger.debugf(\"Manually specify dialect for Oracle to org.hibernate.dialect.Oracle12cDialect\");\n+ return \"org.hibernate.dialect.Oracle12cDialect\";\n+ }\n} catch (SQLException e) {\nlogger.warnf(\"Unable to detect hibernate dialect due database exception : %s\", e.getMessage());\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/pom.xml", "new_path": "testsuite/integration-arquillian/pom.xml", "diff": "</properties>\n</profile>\n<profile>\n- <id>db-allocator-db-oracle12cR1RAC</id>\n+ <id>db-allocator-db-oracleRAC</id>\n<properties>\n<!-- JDBC properties point to \"default\" JDBC driver for the particular DB -->\n<!-- For EAP testing, it is recommended to override those with system properties pointing to GAV of more appropriate JDBC driver -->\n<jdbc.mvn.groupId>com.oracle</jdbc.mvn.groupId>\n<jdbc.mvn.artifactId>ojdbc8</jdbc.mvn.artifactId>\n<jdbc.mvn.version>12.2.0.1</jdbc.mvn.version>\n- <dballocator.type>oracle12cR1RAC</dballocator.type>\n+ <dballocator.type>oracle19cRAC</dballocator.type>\n<dballocator.skip>false</dballocator.skip>\n</properties>\n</profile>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12724 - workaround hibernate bug - set explicitly dialect for oracle version greater than 12
339,281
22.01.2020 20:44:23
-3,600
d6c5f79f2cd7d388780ea29c5ef39707ecdd2f5f
NumberFormatException when starting container
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/migration/ModelVersion.java", "new_path": "server-spi-private/src/main/java/org/keycloak/migration/ModelVersion.java", "diff": "@@ -38,9 +38,9 @@ public class ModelVersion {\n}\npublic ModelVersion(String version) {\n- if (version.endsWith(\"-SNAPSHOT\") || version.endsWith(\"-snapshot\")) {\n+ if (version.toUpperCase().contains(\"-SNAPSHOT\")) {\nsnapshot = true;\n- version = version.substring(0, version.length() - 9);\n+ version = version.toUpperCase().split(\"-SNAPSHOT\")[0];\n}\nString[] split = version.split(\"\\\\.\");\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12236 NumberFormatException when starting container (#6689)
339,643
22.01.2020 20:53:06
-3,600
b90a0307ea04c7179699511aea2862eeb50a42f7
Add certificate timestamp validation Add certificate timestamp validation
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticator.java", "diff": "@@ -61,6 +61,7 @@ public abstract class AbstractX509ClientCertificateAuthenticator implements Auth\npublic static final String ENABLE_OCSP = \"x509-cert-auth.ocsp-checking-enabled\";\npublic static final String ENABLE_CRLDP = \"x509-cert-auth.crldp-checking-enabled\";\npublic static final String CANONICAL_DN = \"x509-cert-auth.canonical-dn-enabled\";\n+ public static final String TIMESTAMP_VALIDATION = \"x509-cert-auth.timestamp-validation-enabled\";\npublic static final String SERIALNUMBER_HEX = \"x509-cert-auth.serialnumber-hex-enabled\";\npublic static final String CRL_RELATIVE_PATH = \"x509-cert-auth.crl-relative-path\";\npublic static final String OCSPRESPONDER_URI = \"x509-cert-auth.ocsp-responder-uri\";\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticatorFactory.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/AbstractX509ClientCertificateAuthenticatorFactory.java", "diff": "@@ -140,6 +140,13 @@ public abstract class AbstractX509ClientCertificateAuthenticatorFactory implemen\nattributeOrPropertyValue.setHelpText(\"A name of user attribute to map the extracted user identity to existing user. The name must be a valid, existing user attribute if User Mapping Method is set to Custom Attribute Mapper. \" +\n\"Multiple values are relevant when attribute mapping is related to multiple values, e.g. 'Certificate Serial Number and IssuerDN'\");\n+ ProviderConfigProperty timestampValidationValue = new ProviderConfigProperty();\n+ timestampValidationValue.setType(BOOLEAN_TYPE);\n+ timestampValidationValue.setName(TIMESTAMP_VALIDATION);\n+ timestampValidationValue.setLabel(\"Check certificate validity\");\n+ timestampValidationValue.setDefaultValue(true);\n+ timestampValidationValue.setHelpText(\"Will verify that the certificate has not expired yet and is already valid by checking the attributes 'notBefore' and 'notAfter'.\");\n+\nProviderConfigProperty crlCheckingEnabled = new ProviderConfigProperty();\ncrlCheckingEnabled.setType(BOOLEAN_TYPE);\ncrlCheckingEnabled.setName(ENABLE_CRL);\n@@ -206,6 +213,7 @@ public abstract class AbstractX509ClientCertificateAuthenticatorFactory implemen\nregExp,\nuserMapperList,\nattributeOrPropertyValue,\n+ timestampValidationValue,\ncrlCheckingEnabled,\ncrlDPEnabled,\ncRLRelativePath,\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/CertificateValidator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/CertificateValidator.java", "diff": "package org.keycloak.authentication.authenticators.x509;\n-import org.keycloak.models.KeycloakSession;\n-import org.keycloak.utils.CRLUtils;\nimport org.keycloak.common.util.OCSPUtils;\n+import org.keycloak.common.util.Time;\nimport org.keycloak.models.Constants;\n+import org.keycloak.models.KeycloakSession;\n+import org.keycloak.saml.common.exceptions.ProcessingException;\n+import org.keycloak.saml.processing.core.util.XMLSignatureUtil;\nimport org.keycloak.services.ServicesLogger;\n+import org.keycloak.truststore.TruststoreProvider;\n+import org.keycloak.utils.CRLUtils;\nimport javax.naming.Context;\nimport javax.naming.NamingException;\n@@ -30,37 +34,33 @@ import javax.naming.directory.Attribute;\nimport javax.naming.directory.Attributes;\nimport javax.naming.directory.DirContext;\nimport javax.naming.directory.InitialDirContext;\n+import javax.security.auth.x500.X500Principal;\nimport java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\n-import java.io.IOException;\n-import java.io.InputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\n+import java.io.IOException;\n+import java.io.InputStream;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URLConnection;\nimport java.security.GeneralSecurityException;\n+import java.security.cert.CRLException;\nimport java.security.cert.CertPathValidatorException;\n+import java.security.cert.CertificateException;\nimport java.security.cert.CertificateFactory;\nimport java.security.cert.X509CRL;\nimport java.security.cert.X509Certificate;\n-import java.security.cert.CertificateException;\n-import java.security.cert.CRLException;\n+import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Hashtable;\n-import java.util.List;\n-import java.util.Set;\nimport java.util.LinkedList;\n-import java.util.ArrayList;\n+import java.util.List;\nimport java.util.Map;\n+import java.util.Set;\nimport java.util.stream.Collectors;\n-import javax.security.auth.x500.X500Principal;\n-\n-import org.keycloak.saml.common.exceptions.ProcessingException;\n-import org.keycloak.saml.processing.core.util.XMLSignatureUtil;\n-import org.keycloak.truststore.TruststoreProvider;\n/**\n* @author <a href=\"mailto:[email protected]\">Peter Nalyvayko</a>\n@@ -468,6 +468,32 @@ public class CertificateValidator {\nreturn this;\n}\n+ public CertificateValidator validateTimestamps(boolean isValidationEnabled) throws GeneralSecurityException {\n+ if (!isValidationEnabled) {\n+ return this;\n+ }\n+ for (int i = 0; i < _certChain.length; i++)\n+ {\n+ X509Certificate x509Certificate = _certChain[i];\n+ if (x509Certificate.getNotBefore().getTime() > Time.currentTimeMillis()) {\n+ String serialNumber = x509Certificate.getSerialNumber().toString(16).replaceAll(\"..(?!$)\",\n+ \"$0 \");\n+ String message =\n+ \"certificate with serialnumber '\" + serialNumber\n+ + \"' is not valid yet: \" + x509Certificate.getNotBefore().toString();\n+ throw new GeneralSecurityException(message);\n+ }\n+ if (x509Certificate.getNotAfter().getTime() < Time.currentTimeMillis()) {\n+ String serialNumber = x509Certificate.getSerialNumber().toString(16).replaceAll(\"..(?!$)\",\n+ \"$0 \");\n+ String message = \"certificate with serialnumber '\" + serialNumber\n+ + \"' has expired on: \" + x509Certificate.getNotAfter().toString();\n+ throw new GeneralSecurityException(message);\n+ }\n+ }\n+ return this;\n+ }\n+\nprivate X509Certificate findCAInTruststore(X500Principal issuer) throws GeneralSecurityException {\nTruststoreProvider truststoreProvider = session.getProvider(TruststoreProvider.class);\nif (truststoreProvider == null || truststoreProvider.getTruststore() == null) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/X509AuthenticatorConfigModel.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/X509AuthenticatorConfigModel.java", "diff": "@@ -254,6 +254,15 @@ public class X509AuthenticatorConfigModel extends AuthenticatorConfigModel {\nreturn this;\n}\n+ public boolean isCertValidationEnabled() {\n+ return Boolean.parseBoolean(getConfig().get(TIMESTAMP_VALIDATION));\n+ }\n+\n+ public X509AuthenticatorConfigModel setCertValidationEnabled(boolean value) {\n+ getConfig().put(TIMESTAMP_VALIDATION, Boolean.toString(value));\n+ return this;\n+ }\n+\npublic boolean isSerialnumberHex() {\nreturn Boolean.parseBoolean(getConfig().get(SERIALNUMBER_HEX));\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/X509ClientCertificateAuthenticator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/x509/X509ClientCertificateAuthenticator.java", "diff": "@@ -84,7 +84,8 @@ public class X509ClientCertificateAuthenticator extends AbstractX509ClientCertif\nCertificateValidator validator = builder.build(certs);\nvalidator.checkRevocationStatus()\n.validateKeyUsage()\n- .validateExtendedKeyUsage();\n+ .validateExtendedKeyUsage()\n+ .validateTimestamps(config.isCertValidationEnabled());\n} catch(Exception e) {\nlogger.error(e.getMessage(), e);\n// TODO use specific locale to load error messages\n" }, { "change_type": "ADD", "old_path": null, "new_path": "services/src/test/java/org/keycloak/authentication/authenticators/x509/CertificateValidatorTest.java", "diff": "+package org.keycloak.authentication.authenticators.x509;\n+\n+import org.bouncycastle.asn1.ASN1Sequence;\n+import org.bouncycastle.asn1.x500.X500Name;\n+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;\n+import org.bouncycastle.cert.X509v3CertificateBuilder;\n+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;\n+import org.bouncycastle.jce.provider.BouncyCastleProvider;\n+import org.bouncycastle.operator.ContentSigner;\n+import org.bouncycastle.operator.OperatorCreationException;\n+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;\n+import org.hamcrest.MatcherAssert;\n+import org.hamcrest.Matchers;\n+import org.junit.Assert;\n+import org.junit.Test;\n+\n+import java.math.BigInteger;\n+import java.security.GeneralSecurityException;\n+import java.security.KeyPair;\n+import java.security.KeyPairGenerator;\n+import java.security.SecureRandom;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+import java.util.Date;\n+\n+/**\n+ * author Pascal Knueppel <br>\n+ * created at: 07.11.2019 - 16:24 <br>\n+ * <br>\n+ *\n+ */\n+public class CertificateValidatorTest {\n+\n+ private static final BouncyCastleProvider BOUNCY_CASTLE_PROVIDER = new BouncyCastleProvider();\n+\n+ /**\n+ * will validate that the certificate validation succeeds if the certificate is currently valid\n+ */\n+ @Test\n+ public void testValidityOfCertificatesSuccess() throws GeneralSecurityException {\n+ KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\");\n+ kpg.initialize(512);\n+ KeyPair keyPair = kpg.generateKeyPair();\n+ X509Certificate certificate =\n+ createCertificate(\"CN=keycloak-test\", new Date(),\n+ new Date(System.currentTimeMillis() + 1000L * 60), keyPair);\n+\n+ CertificateValidator.CertificateValidatorBuilder builder =\n+ new CertificateValidator.CertificateValidatorBuilder();\n+ CertificateValidator validator = builder.build(new X509Certificate[] { certificate });\n+ try {\n+ validator.validateTimestamps(true);\n+ } catch (Exception ex) {\n+ ex.printStackTrace();\n+ Assert.fail(ex.getMessage());\n+ }\n+ }\n+\n+ /**\n+ * will validate that the certificate validation throws an exception if the certificate is not valid yet\n+ */\n+ @Test\n+ public void testValidityOfCertificatesNotValidYet() throws GeneralSecurityException {\n+ KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\");\n+ kpg.initialize(512);\n+ KeyPair keyPair = kpg.generateKeyPair();\n+ X509Certificate certificate =\n+ createCertificate(\"CN=keycloak-test\", new Date(System.currentTimeMillis() + 1000L * 60),\n+ new Date(System.currentTimeMillis() + 1000L * 60), keyPair);\n+\n+ CertificateValidator.CertificateValidatorBuilder builder =\n+ new CertificateValidator.CertificateValidatorBuilder();\n+ CertificateValidator validator = builder.build(new X509Certificate[] { certificate });\n+ try {\n+ validator.validateTimestamps(true);\n+ Assert.fail(\"certificate validation must fail for certificate is not valid yet\");\n+ } catch (Exception ex) {\n+ MatcherAssert.assertThat(ex.getMessage(), Matchers.containsString(\"not valid yet\"));\n+ Assert.assertEquals(GeneralSecurityException.class, ex.getClass());\n+ }\n+ }\n+\n+ /**\n+ * will validate that the certificate validation throws an exception if the certificate has expired\n+ */\n+ @Test\n+ public void testValidityOfCertificatesHasExpired() throws GeneralSecurityException {\n+ KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\");\n+ kpg.initialize(512);\n+ KeyPair keyPair = kpg.generateKeyPair();\n+ X509Certificate certificate =\n+ createCertificate(\"CN=keycloak-test\", new Date(System.currentTimeMillis() - 1000L * 60 * 2),\n+ new Date(System.currentTimeMillis() - 1000L * 60), keyPair);\n+\n+ CertificateValidator.CertificateValidatorBuilder builder =\n+ new CertificateValidator.CertificateValidatorBuilder();\n+ CertificateValidator validator = builder.build(new X509Certificate[] { certificate });\n+ try {\n+ validator.validateTimestamps(true);\n+ Assert.fail(\"certificate validation must fail for certificate has expired\");\n+ } catch (Exception ex) {\n+ MatcherAssert.assertThat(ex.getMessage(), Matchers.containsString(\"has expired\"));\n+ Assert.assertEquals(GeneralSecurityException.class, ex.getClass());\n+ }\n+ }\n+\n+\n+ /**\n+ * will create a self-signed certificate\n+ *\n+ * @param dn the DN of the subject and issuer\n+ * @param startDate startdate of the validity of the created certificate\n+ * @param expiryDate expiration date of the created certificate\n+ * @param keyPair the keypair that is used to create the certificate\n+ * @return a X509-Certificate in version 3\n+ */\n+ public X509Certificate createCertificate(String dn,\n+ Date startDate,\n+ Date expiryDate,\n+ KeyPair keyPair) {\n+ X500Name subjectDN = new X500Name(dn);\n+ X500Name issuerDN = new X500Name(dn);\n+ // @formatter:off\n+ SubjectPublicKeyInfo subjPubKeyInfo = SubjectPublicKeyInfo.getInstance(\n+ ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));\n+ // @formatter:on\n+ BigInteger serialNumber = new BigInteger(130, new SecureRandom());\n+\n+ X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(issuerDN, serialNumber, startDate, expiryDate,\n+ subjectDN, subjPubKeyInfo);\n+ ContentSigner contentSigner = null;\n+ try {\n+ // @formatter:off\n+ contentSigner = new JcaContentSignerBuilder(\"SHA256withRSA\")\n+ .setProvider(BOUNCY_CASTLE_PROVIDER)\n+ .build(keyPair.getPrivate());\n+ X509Certificate x509Certificate = new JcaX509CertificateConverter()\n+ .setProvider(BOUNCY_CASTLE_PROVIDER)\n+ .getCertificate(certGen.build(contentSigner));\n+ // @formatter:on\n+ return x509Certificate;\n+ } catch (CertificateException | OperatorCreationException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ }\n+\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "services/src/test/java/org/keycloak/authentication/authenticators/x509/X509AuthenticatorConfigModelTest.java", "diff": "+package org.keycloak.authentication.authenticators.x509;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+\n+/**\n+ * author Pascal Knueppel <br>\n+ * created at: 02.12.2019 - 10:59 <br>\n+ * <br>\n+ *\n+ */\n+public class X509AuthenticatorConfigModelTest {\n+\n+ /**\n+ * this test will verify that no exception occurs if no settings are stored for the timestamp validation\n+ */\n+ @Test\n+ public void testTimestampValidationAttributeReturnsNull() {\n+ X509AuthenticatorConfigModel configModel = new X509AuthenticatorConfigModel();\n+ Assert.assertNull(configModel.getConfig().get(AbstractX509ClientCertificateAuthenticator.TIMESTAMP_VALIDATION));\n+ Assert.assertFalse(configModel.isCertValidationEnabled());\n+ }\n+}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Add certificate timestamp validation (#6330) KEYCLOAK-11818 Add certificate timestamp validation
339,465
19.12.2019 16:32:05
-3,600
f0d95da52d7e4462c07b12871164fb7b489c0a0d
Fix export/import for users that have custom credential algorithms with no salt
[ { "change_type": "MODIFY", "old_path": "server-spi/src/main/java/org/keycloak/models/credential/dto/PasswordSecretData.java", "new_path": "server-spi/src/main/java/org/keycloak/models/credential/dto/PasswordSecretData.java", "diff": "package org.keycloak.models.credential.dto;\n+import java.io.IOException;\n+\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n+import org.jboss.logging.Logger;\n+import org.keycloak.common.util.Base64;\npublic class PasswordSecretData {\n+\n+ public static final Logger logger = Logger.getLogger(PasswordSecretData.class);\n+\nprivate final String value;\nprivate final byte[] salt;\n@JsonCreator\n- public PasswordSecretData(@JsonProperty(\"value\") String value, @JsonProperty(\"salt\") byte[] salt) {\n+ public PasswordSecretData(@JsonProperty(\"value\") String value, @JsonProperty(\"salt\") String salt) {\n+ this(value, decodeSalt(salt));\n+ }\n+\n+ public PasswordSecretData(String value, byte[] salt) {\nthis.value = value;\nthis.salt = salt;\n}\n+ private static byte[] decodeSalt(String salt) {\n+ try {\n+ return Base64.decode(salt);\n+ } catch (IOException ioe) {\n+ // Could happen under some corner cases that value is still placeholder value \"__SALT__\" . For example when importing JSON from\n+ // previous version and using custom hash provider without salt support.\n+ logger.tracef(\"Can't base64 decode the salt %s . Fallback to null salt\", salt);\n+ return null;\n+ }\n+ }\n+\npublic String getValue() {\nreturn value;\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportUtil.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportUtil.java", "diff": "@@ -28,6 +28,8 @@ import org.keycloak.admin.client.resource.UserResource;\nimport org.keycloak.common.constants.KerberosConstants;\nimport org.keycloak.models.Constants;\nimport org.keycloak.models.LDAPConstants;\n+import org.keycloak.models.credential.PasswordCredentialModel;\n+import org.keycloak.models.credential.dto.PasswordCredentialData;\nimport org.keycloak.models.utils.DefaultAuthenticationFlows;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;\n@@ -39,6 +41,7 @@ import org.keycloak.representations.idm.ClientMappingsRepresentation;\nimport org.keycloak.representations.idm.ClientRepresentation;\nimport org.keycloak.representations.idm.ClientScopeRepresentation;\nimport org.keycloak.representations.idm.ComponentRepresentation;\n+import org.keycloak.representations.idm.CredentialRepresentation;\nimport org.keycloak.representations.idm.FederatedIdentityRepresentation;\nimport org.keycloak.representations.idm.IdentityProviderRepresentation;\nimport org.keycloak.representations.idm.ProtocolMapperRepresentation;\n@@ -58,6 +61,7 @@ import org.keycloak.testsuite.admin.ApiUtil;\nimport org.keycloak.testsuite.client.KeycloakTestingClient;\nimport org.keycloak.testsuite.util.RealmRepUtil;\n+import java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\n@@ -72,6 +76,8 @@ import java.util.stream.Collectors;\nimport org.hamcrest.Matcher;\nimport org.hamcrest.Matchers;\n+import org.keycloak.util.JsonSerialization;\n+\nimport static org.junit.Assert.assertThat;\n/**\n@@ -82,7 +88,7 @@ public class ExportImportUtil {\n// In the old testsuite, this method exists as a public method of ImportTest from the model package.\n// However, model package is not ready to be migrated yet.\n- public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTestingClient testingClient, RealmRepresentation realm) {\n+ public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTestingClient testingClient, RealmRepresentation realm) throws IOException {\nAssert.assertTrue(realm.isVerifyEmail());\nAssert.assertEquals((Integer)3600000, realm.getOfflineSessionIdleTimeout());\nAssert.assertEquals((Integer)1500, realm.getAccessTokenLifespanForImplicitFlow());\n@@ -179,6 +185,13 @@ public class ExportImportUtil {\n// user with creation timestamp as string in import\nAssert.assertEquals(new Long(123655), loginclient.getCreatedTimestamp());\n+ UserRepresentation hashedPasswordUser = findByUsername(realmRsc, \"hashedpassworduser\");\n+ CredentialRepresentation password = realmRsc.users().get(hashedPasswordUser.getId()).credentials().stream()\n+ .filter(credential -> PasswordCredentialModel.TYPE.equals(credential.getType()))\n+ .findFirst().get();\n+ PasswordCredentialData credentialData = JsonSerialization.readValue(password.getCredentialData(), PasswordCredentialData.class);\n+ Assert.assertEquals(1234, credentialData.getHashIterations());\n+\nList<RoleRepresentation> realmRoles = realmRolesForUser(realmRsc, admin);\nAssert.assertEquals(1, realmRoles.size());\nAssert.assertEquals(\"admin\", realmRoles.iterator().next().getName());\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/resources/model/testrealm.json", "new_path": "testsuite/integration-arquillian/tests/base/src/test/resources/model/testrealm.json", "diff": "}\n]\n},\n+ {\n+ \"username\": \"hashedpassworduser\",\n+ \"createdTimestamp\" : \"123655\",\n+ \"enabled\": true,\n+ \"credentials\": [\n+ {\n+ \"id\": \"b0c22f34-f6fb-4165-8fd3-54d3cb4599d1\",\n+ \"type\": \"password\",\n+ \"createdDate\": 1576751136227,\n+ \"secretData\": \"{\\\"value\\\":\\\"pass\\\",\\\"salt\\\":\\\"__SALT__\\\"}\",\n+ \"credentialData\": \"{\\\"hashIterations\\\":1234,\\\"algorithm\\\":\\\"pbkdf2-sha256\\\"}\"\n+ }\n+ ]\n+ },\n{\n\"username\": \"admin\",\n\"enabled\": true,\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12281 Fix export/import for users that have custom credential algorithms with no salt
339,477
20.12.2019 11:32:16
-3,600
476da4f276a6cc996d83a9a4aa8dde6f070f12e8
Not hide exception in email templating
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/email/EmailException.java", "new_path": "server-spi-private/src/main/java/org/keycloak/email/EmailException.java", "diff": "@@ -26,6 +26,10 @@ public class EmailException extends Exception {\nsuper(cause);\n}\n+ public EmailException(String message) {\n+ super(message);\n+ }\n+\npublic EmailException(String message, Throwable cause) {\nsuper(message, cause);\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "new_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "diff": "@@ -28,6 +28,7 @@ import java.util.Locale;\nimport java.util.Map;\nimport java.util.Properties;\n+import org.jboss.logging.Logger;\nimport org.keycloak.broker.provider.BrokeredIdentityContext;\nimport org.keycloak.common.util.ObjectUtil;\nimport org.keycloak.email.EmailException;\n@@ -54,6 +55,7 @@ import org.keycloak.theme.beans.MessageFormatterMethod;\n*/\npublic class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\n+ private static final Logger logger = Logger.getLogger(FreeMarkerEmailTemplateProvider.class);\nprotected KeycloakSession session;\n/**\n* authenticationSession can be null for some email sendings, it is filled only for email sendings performed as part of the authentication session (email verification, password reset, broker link\n@@ -217,6 +219,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\ntextBody = freeMarker.processTemplate(attributes, textTemplate, theme);\n} catch (final FreeMarkerException e) {\ntextBody = null;\n+ logger.warn(\"Failed to template plain text email.\", e);\n}\nString htmlTemplate = String.format(\"html/%s\", template);\nString htmlBody;\n@@ -224,6 +227,11 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\nhtmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme);\n} catch (final FreeMarkerException e) {\nhtmlBody = null;\n+ logger.warn(\"Failed to template html email.\", e);\n+ }\n+\n+ if (textBody == null && htmlBody == null) {\n+ throw new EmailException(\"Both plain text and html are empty!\");\n}\nreturn new EmailTemplate(subject, textBody, htmlBody);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-9837 Not hide exception in email templating
339,477
20.12.2019 15:01:18
-3,600
f07e08ef28896fc1208c48146b7371524deb840b
Not hide exception in email templating - Throws always an Exception
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "new_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "diff": "@@ -38,6 +38,7 @@ import org.keycloak.email.freemarker.beans.EventBean;\nimport org.keycloak.email.freemarker.beans.ProfileBean;\nimport org.keycloak.events.Event;\nimport org.keycloak.events.EventType;\n+import org.keycloak.forms.login.freemarker.model.UrlBean;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.KeycloakUriInfo;\nimport org.keycloak.models.RealmModel;\n@@ -46,7 +47,6 @@ import org.keycloak.sessions.AuthenticationSessionModel;\nimport org.keycloak.theme.FreeMarkerException;\nimport org.keycloak.theme.FreeMarkerUtil;\nimport org.keycloak.theme.Theme;\n-import org.keycloak.forms.login.freemarker.model.UrlBean;\nimport org.keycloak.theme.beans.LinkExpirationFormatterMethod;\nimport org.keycloak.theme.beans.MessageFormatterMethod;\n@@ -219,7 +219,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\ntextBody = freeMarker.processTemplate(attributes, textTemplate, theme);\n} catch (final FreeMarkerException e) {\ntextBody = null;\n- logger.warn(\"Failed to template plain text email.\", e);\n+ throw new EmailException(\"Failed to template plain text email.\", e);\n}\nString htmlTemplate = String.format(\"html/%s\", template);\nString htmlBody;\n@@ -227,11 +227,7 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\nhtmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme);\n} catch (final FreeMarkerException e) {\nhtmlBody = null;\n- logger.warn(\"Failed to template html email.\", e);\n- }\n-\n- if (textBody == null && htmlBody == null) {\n- throw new EmailException(\"Both plain text and html are empty!\");\n+ throw new EmailException(\"Failed to template html email.\", e);\n}\nreturn new EmailTemplate(subject, textBody, htmlBody);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-9837 Not hide exception in email templating - Throws always an Exception
339,477
10.01.2020 11:21:12
-3,600
812b69af1379d5b8ebeaf8f5a53ee95e1bf61999
Not hide exception in email templating - clean code
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "new_path": "services/src/main/java/org/keycloak/email/freemarker/FreeMarkerEmailTemplateProvider.java", "diff": "@@ -55,7 +55,6 @@ import org.keycloak.theme.beans.MessageFormatterMethod;\n*/\npublic class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\n- private static final Logger logger = Logger.getLogger(FreeMarkerEmailTemplateProvider.class);\nprotected KeycloakSession session;\n/**\n* authenticationSession can be null for some email sendings, it is filled only for email sendings performed as part of the authentication session (email verification, password reset, broker link\n@@ -218,7 +217,6 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\ntry {\ntextBody = freeMarker.processTemplate(attributes, textTemplate, theme);\n} catch (final FreeMarkerException e) {\n- textBody = null;\nthrow new EmailException(\"Failed to template plain text email.\", e);\n}\nString htmlTemplate = String.format(\"html/%s\", template);\n@@ -226,7 +224,6 @@ public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {\ntry {\nhtmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme);\n} catch (final FreeMarkerException e) {\n- htmlBody = null;\nthrow new EmailException(\"Failed to template html email.\", e);\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-9837 Not hide exception in email templating - clean code
339,500
23.01.2020 09:38:55
-3,600
1fbee8134b4d11ed6dd3ebdc5cc9ad92d5036296
Remove mvel2 from parent pom and licenses
[ { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "diff": "</license>\n</licenses>\n</dependency>\n- <dependency>\n- <groupId>org.mvel</groupId>\n- <artifactId>mvel2</artifactId>\n- <version>2.4.0.Final</version>\n- <licenses>\n- <license>\n- <name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/mvel/mvel/mvel2-2.4.0.Final/LICENSE.txt</url>\n- </license>\n- </licenses>\n- </dependency>\n<dependency>\n<groupId>com.google.inject.extensions</groupId>\n<artifactId>guice-servlet</artifactId>\n" }, { "change_type": "DELETE", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/org.mvel,mvel2,2.4.0.Final,Apache Software License 2.0.txt", "new_path": null, "diff": "-\n-\n- Apache License\n- Version 2.0, January 2004\n- http://www.apache.org/licenses/\n-\n- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n-\n- 1. Definitions.\n-\n- \"License\" shall mean the terms and conditions for use, reproduction,\n- and distribution as defined by Sections 1 through 9 of this document.\n-\n- \"Licensor\" shall mean the copyright owner or entity authorized by\n- the copyright owner that is granting the License.\n-\n- \"Legal Entity\" shall mean the union of the acting entity and all\n- other entities that control, are controlled by, or are under common\n- control with that entity. For the purposes of this definition,\n- \"control\" means (i) the power, direct or indirect, to cause the\n- direction or management of such entity, whether by contract or\n- otherwise, or (ii) ownership of fifty percent (50%) or more of the\n- outstanding shares, or (iii) beneficial ownership of such entity.\n-\n- \"You\" (or \"Your\") shall mean an individual or Legal Entity\n- exercising permissions granted by this License.\n-\n- \"Source\" form shall mean the preferred form for making modifications,\n- including but not limited to software source code, documentation\n- source, and configuration files.\n-\n- \"Object\" form shall mean any form resulting from mechanical\n- transformation or translation of a Source form, including but\n- not limited to compiled object code, generated documentation,\n- and conversions to other media types.\n-\n- \"Work\" shall mean the work of authorship, whether in Source or\n- Object form, made available under the License, as indicated by a\n- copyright notice that is included in or attached to the work\n- (an example is provided in the Appendix below).\n-\n- \"Derivative Works\" shall mean any work, whether in Source or Object\n- form, that is based on (or derived from) the Work and for which the\n- editorial revisions, annotations, elaborations, or other modifications\n- represent, as a whole, an original work of authorship. For the purposes\n- of this License, Derivative Works shall not include works that remain\n- separable from, or merely link (or bind by name) to the interfaces of,\n- the Work and Derivative Works thereof.\n-\n- \"Contribution\" shall mean any work of authorship, including\n- the original version of the Work and any modifications or additions\n- to that Work or Derivative Works thereof, that is intentionally\n- submitted to Licensor for inclusion in the Work by the copyright owner\n- or by an individual or Legal Entity authorized to submit on behalf of\n- the copyright owner. For the purposes of this definition, \"submitted\"\n- means any form of electronic, verbal, or written communication sent\n- to the Licensor or its representatives, including but not limited to\n- communication on electronic mailing lists, source code control systems,\n- and issue tracking systems that are managed by, or on behalf of, the\n- Licensor for the purpose of discussing and improving the Work, but\n- excluding communication that is conspicuously marked or otherwise\n- designated in writing by the copyright owner as \"Not a Contribution.\"\n-\n- \"Contributor\" shall mean Licensor and any individual or Legal Entity\n- on behalf of whom a Contribution has been received by Licensor and\n- subsequently incorporated within the Work.\n-\n- 2. Grant of Copyright License. Subject to the terms and conditions of\n- this License, each Contributor hereby grants to You a perpetual,\n- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n- copyright license to reproduce, prepare Derivative Works of,\n- publicly display, publicly perform, sublicense, and distribute the\n- Work and such Derivative Works in Source or Object form.\n-\n- 3. Grant of Patent License. Subject to the terms and conditions of\n- this License, each Contributor hereby grants to You a perpetual,\n- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n- (except as stated in this section) patent license to make, have made,\n- use, offer to sell, sell, import, and otherwise transfer the Work,\n- where such license applies only to those patent claims licensable\n- by such Contributor that are necessarily infringed by their\n- Contribution(s) alone or by combination of their Contribution(s)\n- with the Work to which such Contribution(s) was submitted. If You\n- institute patent litigation against any entity (including a\n- cross-claim or counterclaim in a lawsuit) alleging that the Work\n- or a Contribution incorporated within the Work constitutes direct\n- or contributory patent infringement, then any patent licenses\n- granted to You under this License for that Work shall terminate\n- as of the date such litigation is filed.\n-\n- 4. Redistribution. You may reproduce and distribute copies of the\n- Work or Derivative Works thereof in any medium, with or without\n- modifications, and in Source or Object form, provided that You\n- meet the following conditions:\n-\n- (a) You must give any other recipients of the Work or\n- Derivative Works a copy of this License; and\n-\n- (b) You must cause any modified files to carry prominent notices\n- stating that You changed the files; and\n-\n- (c) You must retain, in the Source form of any Derivative Works\n- that You distribute, all copyright, patent, trademark, and\n- attribution notices from the Source form of the Work,\n- excluding those notices that do not pertain to any part of\n- the Derivative Works; and\n-\n- (d) If the Work includes a \"NOTICE\" text file as part of its\n- distribution, then any Derivative Works that You distribute must\n- include a readable copy of the attribution notices contained\n- within such NOTICE file, excluding those notices that do not\n- pertain to any part of the Derivative Works, in at least one\n- of the following places: within a NOTICE text file distributed\n- as part of the Derivative Works; within the Source form or\n- documentation, if provided along with the Derivative Works; or,\n- within a display generated by the Derivative Works, if and\n- wherever such third-party notices normally appear. The contents\n- of the NOTICE file are for informational purposes only and\n- do not modify the License. You may add Your own attribution\n- notices within Derivative Works that You distribute, alongside\n- or as an addendum to the NOTICE text from the Work, provided\n- that such additional attribution notices cannot be construed\n- as modifying the License.\n-\n- You may add Your own copyright statement to Your modifications and\n- may provide additional or different license terms and conditions\n- for use, reproduction, or distribution of Your modifications, or\n- for any such Derivative Works as a whole, provided Your use,\n- reproduction, and distribution of the Work otherwise complies with\n- the conditions stated in this License.\n-\n- 5. Submission of Contributions. Unless You explicitly state otherwise,\n- any Contribution intentionally submitted for inclusion in the Work\n- by You to the Licensor shall be under the terms and conditions of\n- this License, without any additional terms or conditions.\n- Notwithstanding the above, nothing herein shall supersede or modify\n- the terms of any separate license agreement you may have executed\n- with Licensor regarding such Contributions.\n-\n- 6. Trademarks. This License does not grant permission to use the trade\n- names, trademarks, service marks, or product names of the Licensor,\n- except as required for reasonable and customary use in describing the\n- origin of the Work and reproducing the content of the NOTICE file.\n-\n- 7. Disclaimer of Warranty. Unless required by applicable law or\n- agreed to in writing, Licensor provides the Work (and each\n- Contributor provides its Contributions) on an \"AS IS\" BASIS,\n- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n- implied, including, without limitation, any warranties or conditions\n- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n- PARTICULAR PURPOSE. You are solely responsible for determining the\n- appropriateness of using or redistributing the Work and assume any\n- risks associated with Your exercise of permissions under this License.\n-\n- 8. Limitation of Liability. In no event and under no legal theory,\n- whether in tort (including negligence), contract, or otherwise,\n- unless required by applicable law (such as deliberate and grossly\n- negligent acts) or agreed to in writing, shall any Contributor be\n- liable to You for damages, including any direct, indirect, special,\n- incidental, or consequential damages of any character arising as a\n- result of this License or out of the use or inability to use the\n- Work (including but not limited to damages for loss of goodwill,\n- work stoppage, computer failure or malfunction, or any and all\n- other commercial damages or losses), even if such Contributor\n- has been advised of the possibility of such damages.\n-\n- 9. Accepting Warranty or Additional Liability. While redistributing\n- the Work or Derivative Works thereof, You may choose to offer,\n- and charge a fee for, acceptance of support, warranty, indemnity,\n- or other liability obligations and/or rights consistent with this\n- License. However, in accepting such obligations, You may act only\n- on Your own behalf and on Your sole responsibility, not on behalf\n- of any other Contributor, and only if You agree to indemnify,\n- defend, and hold each Contributor harmless for any liability\n- incurred by, or claims asserted against, such Contributor by reason\n- of your accepting any such warranty or additional liability.\n-\n" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "diff": "</license>\n</licenses>\n</dependency>\n- <dependency>\n- <groupId>org.mvel</groupId>\n- <artifactId>mvel2</artifactId>\n- <version>2.4.0.Final</version>\n- <licenses>\n- <license>\n- <name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/mvel/mvel/mvel2-2.4.0.Final/LICENSE.txt</url>\n- </license>\n- </licenses>\n- </dependency>\n<dependency>\n<groupId>com.google.inject.extensions</groupId>\n<artifactId>guice-servlet</artifactId>\n" }, { "change_type": "DELETE", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/org.mvel,mvel2,2.4.0.Final,Apache Software License 2.0.txt", "new_path": null, "diff": "-\n-\n- Apache License\n- Version 2.0, January 2004\n- http://www.apache.org/licenses/\n-\n- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n-\n- 1. Definitions.\n-\n- \"License\" shall mean the terms and conditions for use, reproduction,\n- and distribution as defined by Sections 1 through 9 of this document.\n-\n- \"Licensor\" shall mean the copyright owner or entity authorized by\n- the copyright owner that is granting the License.\n-\n- \"Legal Entity\" shall mean the union of the acting entity and all\n- other entities that control, are controlled by, or are under common\n- control with that entity. For the purposes of this definition,\n- \"control\" means (i) the power, direct or indirect, to cause the\n- direction or management of such entity, whether by contract or\n- otherwise, or (ii) ownership of fifty percent (50%) or more of the\n- outstanding shares, or (iii) beneficial ownership of such entity.\n-\n- \"You\" (or \"Your\") shall mean an individual or Legal Entity\n- exercising permissions granted by this License.\n-\n- \"Source\" form shall mean the preferred form for making modifications,\n- including but not limited to software source code, documentation\n- source, and configuration files.\n-\n- \"Object\" form shall mean any form resulting from mechanical\n- transformation or translation of a Source form, including but\n- not limited to compiled object code, generated documentation,\n- and conversions to other media types.\n-\n- \"Work\" shall mean the work of authorship, whether in Source or\n- Object form, made available under the License, as indicated by a\n- copyright notice that is included in or attached to the work\n- (an example is provided in the Appendix below).\n-\n- \"Derivative Works\" shall mean any work, whether in Source or Object\n- form, that is based on (or derived from) the Work and for which the\n- editorial revisions, annotations, elaborations, or other modifications\n- represent, as a whole, an original work of authorship. For the purposes\n- of this License, Derivative Works shall not include works that remain\n- separable from, or merely link (or bind by name) to the interfaces of,\n- the Work and Derivative Works thereof.\n-\n- \"Contribution\" shall mean any work of authorship, including\n- the original version of the Work and any modifications or additions\n- to that Work or Derivative Works thereof, that is intentionally\n- submitted to Licensor for inclusion in the Work by the copyright owner\n- or by an individual or Legal Entity authorized to submit on behalf of\n- the copyright owner. For the purposes of this definition, \"submitted\"\n- means any form of electronic, verbal, or written communication sent\n- to the Licensor or its representatives, including but not limited to\n- communication on electronic mailing lists, source code control systems,\n- and issue tracking systems that are managed by, or on behalf of, the\n- Licensor for the purpose of discussing and improving the Work, but\n- excluding communication that is conspicuously marked or otherwise\n- designated in writing by the copyright owner as \"Not a Contribution.\"\n-\n- \"Contributor\" shall mean Licensor and any individual or Legal Entity\n- on behalf of whom a Contribution has been received by Licensor and\n- subsequently incorporated within the Work.\n-\n- 2. Grant of Copyright License. Subject to the terms and conditions of\n- this License, each Contributor hereby grants to You a perpetual,\n- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n- copyright license to reproduce, prepare Derivative Works of,\n- publicly display, publicly perform, sublicense, and distribute the\n- Work and such Derivative Works in Source or Object form.\n-\n- 3. Grant of Patent License. Subject to the terms and conditions of\n- this License, each Contributor hereby grants to You a perpetual,\n- worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n- (except as stated in this section) patent license to make, have made,\n- use, offer to sell, sell, import, and otherwise transfer the Work,\n- where such license applies only to those patent claims licensable\n- by such Contributor that are necessarily infringed by their\n- Contribution(s) alone or by combination of their Contribution(s)\n- with the Work to which such Contribution(s) was submitted. If You\n- institute patent litigation against any entity (including a\n- cross-claim or counterclaim in a lawsuit) alleging that the Work\n- or a Contribution incorporated within the Work constitutes direct\n- or contributory patent infringement, then any patent licenses\n- granted to You under this License for that Work shall terminate\n- as of the date such litigation is filed.\n-\n- 4. Redistribution. You may reproduce and distribute copies of the\n- Work or Derivative Works thereof in any medium, with or without\n- modifications, and in Source or Object form, provided that You\n- meet the following conditions:\n-\n- (a) You must give any other recipients of the Work or\n- Derivative Works a copy of this License; and\n-\n- (b) You must cause any modified files to carry prominent notices\n- stating that You changed the files; and\n-\n- (c) You must retain, in the Source form of any Derivative Works\n- that You distribute, all copyright, patent, trademark, and\n- attribution notices from the Source form of the Work,\n- excluding those notices that do not pertain to any part of\n- the Derivative Works; and\n-\n- (d) If the Work includes a \"NOTICE\" text file as part of its\n- distribution, then any Derivative Works that You distribute must\n- include a readable copy of the attribution notices contained\n- within such NOTICE file, excluding those notices that do not\n- pertain to any part of the Derivative Works, in at least one\n- of the following places: within a NOTICE text file distributed\n- as part of the Derivative Works; within the Source form or\n- documentation, if provided along with the Derivative Works; or,\n- within a display generated by the Derivative Works, if and\n- wherever such third-party notices normally appear. The contents\n- of the NOTICE file are for informational purposes only and\n- do not modify the License. You may add Your own attribution\n- notices within Derivative Works that You distribute, alongside\n- or as an addendum to the NOTICE text from the Work, provided\n- that such additional attribution notices cannot be construed\n- as modifying the License.\n-\n- You may add Your own copyright statement to Your modifications and\n- may provide additional or different license terms and conditions\n- for use, reproduction, or distribution of Your modifications, or\n- for any such Derivative Works as a whole, provided Your use,\n- reproduction, and distribution of the Work otherwise complies with\n- the conditions stated in this License.\n-\n- 5. Submission of Contributions. Unless You explicitly state otherwise,\n- any Contribution intentionally submitted for inclusion in the Work\n- by You to the Licensor shall be under the terms and conditions of\n- this License, without any additional terms or conditions.\n- Notwithstanding the above, nothing herein shall supersede or modify\n- the terms of any separate license agreement you may have executed\n- with Licensor regarding such Contributions.\n-\n- 6. Trademarks. This License does not grant permission to use the trade\n- names, trademarks, service marks, or product names of the Licensor,\n- except as required for reasonable and customary use in describing the\n- origin of the Work and reproducing the content of the NOTICE file.\n-\n- 7. Disclaimer of Warranty. Unless required by applicable law or\n- agreed to in writing, Licensor provides the Work (and each\n- Contributor provides its Contributions) on an \"AS IS\" BASIS,\n- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n- implied, including, without limitation, any warranties or conditions\n- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n- PARTICULAR PURPOSE. You are solely responsible for determining the\n- appropriateness of using or redistributing the Work and assume any\n- risks associated with Your exercise of permissions under this License.\n-\n- 8. Limitation of Liability. In no event and under no legal theory,\n- whether in tort (including negligence), contract, or otherwise,\n- unless required by applicable law (such as deliberate and grossly\n- negligent acts) or agreed to in writing, shall any Contributor be\n- liable to You for damages, including any direct, indirect, special,\n- incidental, or consequential damages of any character arising as a\n- result of this License or out of the use or inability to use the\n- Work (including but not limited to damages for loss of goodwill,\n- work stoppage, computer failure or malfunction, or any and all\n- other commercial damages or losses), even if such Contributor\n- has been advised of the possibility of such damages.\n-\n- 9. Accepting Warranty or Additional Liability. While redistributing\n- the Work or Derivative Works thereof, You may choose to offer,\n- and charge a fee for, acceptance of support, warranty, indemnity,\n- or other liability obligations and/or rights consistent with this\n- License. However, in accepting such obligations, You may act only\n- on Your own behalf and on Your sole responsibility, not on behalf\n- of any other Contributor, and only if You agree to indemnify,\n- defend, and hold each Contributor harmless for any liability\n- incurred by, or claims asserted against, such Contributor by reason\n- of your accepting any such warranty or additional liability.\n-\n" }, { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<webauthn4j.version>0.9.14.RELEASE</webauthn4j.version>\n<org.apache.kerby.kerby-asn1.version>2.0.0</org.apache.kerby.kerby-asn1.version>\n- <mvel.version>2.4.0.Final</mvel.version>\n-\n</properties>\n<url>http://keycloak.org</url>\n<artifactId>commons-lang3</artifactId>\n<version>${commons-lang3.version}</version>\n</dependency>\n- <dependency>\n- <groupId>org.mvel</groupId>\n- <artifactId>mvel2</artifactId>\n- <version>${mvel.version}</version>\n- </dependency>\n</dependencies>\n</dependencyManagement>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/pom.xml", "new_path": "testsuite/integration-arquillian/tests/base/pom.xml", "diff": "<!--exclude cluster tests by default, enabled by 'auth-server-*-cluster' profiles in tests/pom.xml-->\n<exclude.cluster>**/cluster/**/*Test.java</exclude.cluster>\n<exclude.crossdc>**/crossdc/**/*Test.java</exclude.crossdc>\n+ <mvel.version>2.4.0.Final</mvel.version>\n</properties>\n<dependencies>\n<dependency>\n<groupId>org.mvel</groupId>\n<artifactId>mvel2</artifactId>\n+ <version>${mvel.version}</version>\n</dependency>\n</dependencies>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12697 Remove mvel2 from parent pom and licenses
339,328
22.11.2019 17:02:06
-3,600
f1ddd5016fb8e9c96ba929ef028e5ee4e0637b3f
Add account api roles to the client on creation
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo9_0_0.java", "new_path": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo9_0_0.java", "diff": "@@ -25,6 +25,7 @@ import org.keycloak.models.Constants;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.ProtocolMapperModel;\nimport org.keycloak.models.RealmModel;\n+import org.keycloak.models.RoleModel;\nimport org.keycloak.models.utils.KeycloakModelUtils;\nimport org.keycloak.representations.idm.RealmRepresentation;\n@@ -45,7 +46,7 @@ public class MigrateTo9_0_0 implements Migration {\n@Override\npublic void migrate(KeycloakSession session) {\n- session.realms().getRealms().stream().forEach(realm -> addAccountConsoleClient(realm));\n+ session.realms().getRealms().stream().forEach(realm -> migrateRealmCommon(realm));\n}\n@Override\n@@ -55,6 +56,22 @@ public class MigrateTo9_0_0 implements Migration {\nprotected void migrateRealmCommon(RealmModel realm) {\naddAccountConsoleClient(realm);\n+ addAccountApiRoles(realm);\n+ }\n+\n+ private void addAccountApiRoles(RealmModel realm) {\n+ ClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);\n+ RoleModel viewAppRole = accountClient.addRole(AccountRoles.VIEW_APPLICATIONS);\n+ viewAppRole.setDescription(\"${role_\" + AccountRoles.VIEW_APPLICATIONS + \"}\");\n+ LOG.debugf(\"Added the role %s to the '%s' client.\", AccountRoles.VIEW_APPLICATIONS, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);\n+ RoleModel viewConsentRole = accountClient.addRole(AccountRoles.VIEW_CONSENT);\n+ viewConsentRole.setDescription(\"${role_\" + AccountRoles.VIEW_CONSENT + \"}\");\n+ LOG.debugf(\"Added the role %s to the '%s' client.\", AccountRoles.VIEW_CONSENT, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);\n+ RoleModel manageConsentRole = accountClient.addRole(AccountRoles.MANAGE_CONSENT);\n+ manageConsentRole.setDescription(\"${role_\" + AccountRoles.MANAGE_CONSENT + \"}\");\n+ LOG.debugf(\"Added the role %s to the '%s' client.\", AccountRoles.MANAGE_CONSENT, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);\n+ manageConsentRole.addCompositeRole(viewConsentRole);\n+ LOG.debugf(\"Added the %s role as a composite role to %s\", AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT);\n}\nprotected void addAccountConsoleClient(RealmModel realm) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/managers/RealmManager.java", "new_path": "services/src/main/java/org/keycloak/services/managers/RealmManager.java", "diff": "package org.keycloak.services.managers;\nimport org.keycloak.Config;\n+import org.keycloak.common.Profile;\nimport org.keycloak.common.enums.SslRequired;\nimport org.keycloak.migration.MigrationModelManager;\nimport org.keycloak.models.AccountRoles;\n@@ -428,6 +429,13 @@ public class RealmManager {\nmanageAccountLinks.setDescription(\"${role_\" + AccountRoles.MANAGE_ACCOUNT_LINKS + \"}\");\nRoleModel manageAccount = accountClient.getRole(AccountRoles.MANAGE_ACCOUNT);\nmanageAccount.addCompositeRole(manageAccountLinks);\n+ RoleModel viewAppRole = accountClient.addRole(AccountRoles.VIEW_APPLICATIONS);\n+ viewAppRole.setDescription(\"${role_\" + AccountRoles.VIEW_APPLICATIONS + \"}\");\n+ RoleModel viewConsentRole = accountClient.addRole(AccountRoles.VIEW_CONSENT);\n+ viewConsentRole.setDescription(\"${role_\" + AccountRoles.VIEW_CONSENT + \"}\");\n+ RoleModel manageConsentRole = accountClient.addRole(AccountRoles.MANAGE_CONSENT);\n+ manageConsentRole.setDescription(\"${role_\" + AccountRoles.MANAGE_CONSENT + \"}\");\n+ manageConsentRole.addCompositeRole(viewConsentRole);\nClientModel accountConsoleClient = realm.getClientByClientId(Constants.ACCOUNT_CONSOLE_CLIENT_ID);\nif (accountConsoleClient == null) {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ClientTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ClientTest.java", "diff": "@@ -478,7 +478,8 @@ public class ClientTest extends AbstractAdminTest {\nAssert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll(), AccountRoles.VIEW_PROFILE);\nAssert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective(), AccountRoles.VIEW_PROFILE);\n- Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS);\n+ Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS,\n+ AccountRoles.VIEW_APPLICATIONS, AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT);\nAssert.assertNames(scopesResource.getAll().getRealmMappings(), \"role1\");\nAssert.assertNames(scopesResource.getAll().getClientMappings().get(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings(), AccountRoles.VIEW_PROFILE);\n@@ -493,7 +494,8 @@ public class ClientTest extends AbstractAdminTest {\nAssert.assertNames(scopesResource.realmLevel().listEffective());\nAssert.assertNames(scopesResource.realmLevel().listAvailable(), \"offline_access\", Constants.AUTHZ_UMA_AUTHORIZATION, \"role1\", \"role2\");\nAssert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll());\n- Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS);\n+ Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS,\n+ AccountRoles.VIEW_APPLICATIONS, AccountRoles.VIEW_CONSENT, AccountRoles.MANAGE_CONSENT);\nAssert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective());\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java", "diff": "@@ -33,6 +33,7 @@ import org.keycloak.broker.provider.util.SimpleHttp;\nimport org.keycloak.common.constants.KerberosConstants;\nimport org.keycloak.component.PrioritizedComponentModel;\nimport org.keycloak.keys.KeyProvider;\n+import org.keycloak.models.AccountRoles;\nimport org.keycloak.models.AdminRoles;\nimport org.keycloak.models.AuthenticationExecutionModel;\nimport org.keycloak.models.Constants;\n@@ -278,6 +279,25 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {\ntestAlwaysDisplayInConsole();\ntestFirstBrokerLoginFlowMigrated(masterRealm);\ntestFirstBrokerLoginFlowMigrated(migrationRealm);\n+ testAccountClient(masterRealm);\n+ testAccountClient(migrationRealm);\n+ }\n+\n+ private void testAccountClient(RealmResource realm) {\n+ ClientRepresentation accountClient = realm.clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0);\n+\n+ ClientResource accountResource = realm.clients().get(accountClient.getId());\n+ RoleRepresentation viewAppRole = accountResource.roles().get(AccountRoles.VIEW_APPLICATIONS).toRepresentation();\n+ assertNotNull(viewAppRole);\n+ RoleRepresentation viewConsentRole = accountResource.roles().get(AccountRoles.VIEW_CONSENT).toRepresentation();\n+ assertNotNull(viewConsentRole);\n+ RoleResource manageConsentResource = accountResource.roles().get(AccountRoles.MANAGE_CONSENT);\n+ RoleRepresentation manageConsentRole = manageConsentResource.toRepresentation();\n+ assertNotNull(manageConsentRole);\n+ assertTrue(manageConsentRole.isComposite());\n+ Set<RoleRepresentation> composites = manageConsentResource.getRoleComposites();\n+ assertEquals(1, composites.size());\n+ assertEquals(viewConsentRole.getId(), composites.iterator().next().getId());\n}\nprivate void testAdminClientUrls(RealmResource realm) {\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/account/messages/messages_en.properties", "new_path": "themes/src/main/resources/theme/base/account/messages/messages_en.properties", "diff": "@@ -71,6 +71,7 @@ role_view-applications=View applications\nrole_view-clients=View clients\nrole_view-events=View events\nrole_view-identity-providers=View identity providers\n+role_view-consent=View consents\nrole_manage-realm=Manage realm\nrole_manage-users=Manage users\nrole_manage-applications=Manage applications\n@@ -80,6 +81,7 @@ role_manage-events=Manage events\nrole_view-profile=View profile\nrole_manage-account=Manage account\nrole_manage-account-links=Manage account links\n+role_manage-consent=Manage consents\nrole_read-token=Read token\nrole_offline-access=Offline access\nrole_uma_authorization=Obtain permissions\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-11821 Add account api roles to the client on creation Co-authored-by: stianst <[email protected]>
339,414
24.01.2020 11:55:20
-3,600
24c6e2ba088fb0b05fbb93c472b7231aed1dfea3
Authentication -> WebAuthn Policy: Unable to delete the Acceptable AAGUIDS via the provided minus (-) button, once set
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java", "diff": "@@ -1034,8 +1034,9 @@ public class RealmAdapter implements RealmModel, JpaModel<RealmEntity> {\nif (acceptableAaguids != null && !acceptableAaguids.isEmpty()) {\nString acceptableAaguidsString = String.join(\",\", acceptableAaguids);\nsetAttribute(RealmAttributes.WEBAUTHN_POLICY_ACCEPTABLE_AAGUIDS, acceptableAaguidsString);\n+ } else {\n+ removeAttribute(RealmAttributes.WEBAUTHN_POLICY_ACCEPTABLE_AAGUIDS);\n}\n-\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/realm/RealmTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/realm/RealmTest.java", "diff": "@@ -68,13 +68,7 @@ import javax.ws.rs.BadRequestException;\nimport javax.ws.rs.NotFoundException;\nimport javax.ws.rs.core.Response;\nimport java.io.IOException;\n-import java.util.Arrays;\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.*;\nimport java.util.stream.Collectors;\nimport static org.hamcrest.Matchers.containsInAnyOrder;\n@@ -446,10 +440,15 @@ public class RealmTest extends AbstractAdminTest {\npublic void updateRealmAttributes() {\n// first change\nRealmRepresentation rep = new RealmRepresentation();\n+ List<String> webAuthnPolicyAcceptableAaguids = new ArrayList<>();\n+ webAuthnPolicyAcceptableAaguids.add(\"aaguid1\");\n+ webAuthnPolicyAcceptableAaguids.add(\"aaguid2\");\n+\nrep.setAttributes(new HashMap<>());\nrep.getAttributes().put(\"foo1\", \"bar1\");\nrep.getAttributes().put(\"foo2\", \"bar2\");\n+ rep.setWebAuthnPolicyAcceptableAaguids(webAuthnPolicyAcceptableAaguids);\nrep.setBruteForceProtected(true);\nrep.setDisplayName(\"dn1\");\n@@ -457,17 +456,19 @@ public class RealmTest extends AbstractAdminTest {\nassertAdminEvents.assertEvent(realmId, OperationType.UPDATE, Matchers.nullValue(String.class), rep, ResourceType.REALM);\nrep = realm.toRepresentation();\n-\nassertEquals(\"bar1\", rep.getAttributes().get(\"foo1\"));\nassertEquals(\"bar2\", rep.getAttributes().get(\"foo2\"));\nassertTrue(rep.isBruteForceProtected());\nassertEquals(\"dn1\", rep.getDisplayName());\n+ assertEquals(webAuthnPolicyAcceptableAaguids, rep.getWebAuthnPolicyAcceptableAaguids());\n// second change\n+ webAuthnPolicyAcceptableAaguids.clear();\nrep.setBruteForceProtected(false);\nrep.setDisplayName(\"dn2\");\nrep.getAttributes().put(\"foo1\", \"bar11\");\nrep.getAttributes().remove(\"foo2\");\n+ rep.setWebAuthnPolicyAcceptableAaguids(webAuthnPolicyAcceptableAaguids);\nrealm.update(rep);\nassertAdminEvents.assertEvent(realmId, OperationType.UPDATE, Matchers.nullValue(String.class), rep, ResourceType.REALM);\n@@ -479,6 +480,7 @@ public class RealmTest extends AbstractAdminTest {\nassertEquals(\"bar11\", rep.getAttributes().get(\"foo1\"));\nassertFalse(rep.getAttributes().containsKey(\"foo2\"));\n+ assertTrue(rep.getWebAuthnPolicyAcceptableAaguids().isEmpty());\n}\n@Test\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/webauthn-policy.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/webauthn-policy.html", "diff": "<label for=\"type\" class=\"col-md-2 control-label\">{{:: 'webauthn-acceptable-aaguids' | translate}}</label>\n<div class=\"col-sm-4\">\n<div class=\"input-group\" ng-repeat=\"(i, acceptableAaguid) in realm.webAuthnPolicyAcceptableAaguids track by $index\">\n- <input class=\"form-control\" ng-model=\"realm.webAuthnPolicyAcceptableAaguids[i]\">\n+ <input id=\"type\" class=\"form-control\" ng-model=\"realm.webAuthnPolicyAcceptableAaguids[i]\">\n<div class=\"input-group-btn\">\n<button class=\"btn btn-default\" type=\"button\" data-ng-click=\"deleteAcceptableAaguid($index)\">\n<span class=\"fa fa-minus\"></span>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12742 Authentication -> WebAuthn Policy: Unable to delete the Acceptable AAGUIDS via the provided minus (-) button, once set (#6695)
339,209
21.01.2020 10:22:48
25,200
1a53110bb61be27a5cca5af267cfc2d1dd36df6b
Filter out cruft from account2 modules
[ { "change_type": "MODIFY", "old_path": "themes/pom.xml", "new_path": "themes/pom.xml", "diff": "<exclude>**/Gruntfile.js</exclude>\n<exclude>**/Gemfile*</exclude>\n<exclude>**/.*</exclude>\n+ <!-- Remove once account2 manual filter list is removed -->\n+ <exclude>**/keycloak-preview/account/resources/node_modules/**</exclude>\n</excludes>\n</resource>\n+ <!-- account2 manual filter list -->\n+ <!--\n+ To update, use network log in browser, navigate around account2, export\n+ log as HAR json, then run this command to get the new list of includes:\n+ jq -r '.log.entries | .[] | .request.url' /tmp/localhost.har | sed -r 's|^.*/keycloak-preview/(node_modules/.*)$|<include>**/\\1</include>|;tx;d;:x' | sort -Vu | xclip -selection clipboard\n+ -->\n+ <resource>\n+ <directory>src/main/resources</directory>\n+ <includes>\n+ <include>**/node_modules/axios/dist/axios.min.js</include>\n+ <include>**/node_modules/camel-case/camel-case.js</include>\n+ <include>**/node_modules/emotion/dist/emotion.umd.min.js</include>\n+ <include>**/node_modules/exenv/index.js</include>\n+ <include>**/node_modules/focus-trap-react/dist/focus-trap-react.js</include>\n+ <include>**/node_modules/focus-trap/dist/focus-trap.min.js</include>\n+ <include>**/node_modules/lower-case/lower-case.js</include>\n+ <include>**/node_modules/moment/min/moment-with-locales.min.js</include>\n+ <include>**/node_modules/no-case/no-case.js</include>\n+ <include>**/node_modules/no-case/vendor/camel-case-regexp.js</include>\n+ <include>**/node_modules/no-case/vendor/camel-case-upper-regexp.js</include>\n+ <include>**/node_modules/no-case/vendor/non-word-regexp.js</include>\n+ <include>**/node_modules/prop-types/prop-types.min.js</include>\n+ <include>**/node_modules/react-dom/umd/react-dom.production.min.js</include>\n+ <include>**/node_modules/react-router-dom/umd/react-router-dom.min.js</include>\n+ <include>**/node_modules/react/umd/react.production.min.js</include>\n+ <include>**/node_modules/systemjs/dist/system.src.js</include>\n+ <include>**/node_modules/tippy.js/dist/tippy.min.js</include>\n+ <include>**/node_modules/upper-case/upper-case.js</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-bold.ttf</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-bold.woff2</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-bold.woff</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-light-italic.woff2</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-light.woff2</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-regular.woff2</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-semibold.ttf</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-semibold.woff2</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/overpass-webfont/overpass-semibold.woff</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/webfonts/fa-solid-900.ttf</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/webfonts/fa-solid-900.woff</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/webfonts/fa-solid-900.ttf</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/images/img_avatar.svg</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/pficon/pficon.woff2</include>\n+ <include>**/node_modules/@patternfly/patternfly/patternfly.min.css</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Alert/AlertActionCloseButton.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Alert/AlertActionLink.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Alert/AlertIcon.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Alert/Alert.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Alert/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Avatar/Avatar.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Avatar/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Backdrop/Backdrop.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Backdrop/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/BackgroundImage/BackgroundImage.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/BackgroundImage/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Badge/Badge.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Badge/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Brand/Brand.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Brand/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Button/Button.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Button/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Card/Card.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Card/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/ChipGroup/ChipButton.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/ChipGroup/ChipGroupToolbarItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/ChipGroup/ChipGroup.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/ChipGroup/Chip.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/ChipGroup/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListAction.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListCell.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListCheck.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListContent.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListItemCells.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListItemRow.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataListToggle.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/DataList.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/DataList/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/DropdownGroup.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/DropdownItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/DropdownMenu.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/DropdownToggleCheckbox.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/DropdownToggle.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/Dropdown.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/Item.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/KebabToggle.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/Separator.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/Toggle.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/dropdownConstants.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Dropdown/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/EmptyState/EmptyStateBody.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/EmptyState/EmptyStateIcon.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/EmptyState/EmptyStateSecondaryActions.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/EmptyState/EmptyState.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/EmptyState/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Form/ActionGroup.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Form/FormContext.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Form/FormGroup.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Form/FormHelperText.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Form/Form.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Form/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/ModalBoxBody.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/ModalBoxCloseButton.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/ModalBoxFooter.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/ModalBoxHeader.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/ModalBox.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/ModalContent.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/Modal.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Modal/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/NavExpandable.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/NavGroup.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/NavItemSeparator.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/NavItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/NavList.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/NavVariants.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/Nav.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Nav/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Page/PageHeader.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Page/PageSection.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Page/PageSidebar.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Page/Page.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Page/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Switch/Switch.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Switch/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tabs/TabContent.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tabs/Tabs.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tabs/Tab.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tabs/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/TextInput/TextInput.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/TextInput/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Text/TextContent.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Text/TextListItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Text/TextList.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Text/Text.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Text/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Title/Title.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Title/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tooltip/TooltipArrow.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tooltip/TooltipContent.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tooltip/Tooltip.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tooltip/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/Tooltip/styles.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/components/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/helpers/GenerateId/GenerateId.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/helpers/componentShape.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/helpers/constants.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/helpers/htmlConstants.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/helpers/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/helpers/typeUtils.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/helpers/util.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Bullseye/Bullseye.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Bullseye/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Gallery/GalleryItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Gallery/Gallery.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Gallery/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Grid/GridItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Grid/Grid.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Grid/gridUtils.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Grid/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Level/LevelItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Level/Level.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Level/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Stack/StackItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Stack/Stack.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Stack/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Toolbar/ToolbarGroup.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Toolbar/ToolbarItem.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Toolbar/ToolbarSection.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Toolbar/Toolbar.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/Toolbar/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/layouts/index.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/styles/gutters.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/styles/sizes.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Alert/alert.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/AppLauncher/app-launcher.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Avatar/avatar.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Backdrop/backdrop.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/BackgroundImage/background-image.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Badge/badge.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Button/button.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Card/card.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/ChipGroup/chip-group.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Chip/chip.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Content/content.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/DataList/data-list.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Dropdown/dropdown.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/EmptyState/empty-state.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/FormControl/form-control.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Form/form.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/ModalBox/modal-box.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Nav/nav.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Page/page.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Switch/switch.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Tabs/tabs.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Title/title.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/components/Tooltip/tooltip.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/layouts/Bullseye/bullseye.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/layouts/Gallery/gallery.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/layouts/Grid/grid.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/layouts/Level/level.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/layouts/Stack/stack.css.js</include>\n+ <include>**/node_modules/@patternfly/react-core/dist/umd/@patternfly/patternfly/utilities/Accessibility/accessibility.css.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/common.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/createIcon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/amazon-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/angle-down-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/angle-left-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/angle-right-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/arrow-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/bars-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/bitbucket-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/builder-image-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/caret-down-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/check-circle-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/check-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/chrome-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/cube-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/edge-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/edit-alt-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/ellipsis-v-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/exclamation-circle-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/exclamation-triangle-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/facebook-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/firefox-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/github-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/gitlab-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/globe-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/google-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/info-alt-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/info-circle-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/instagram-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/internet-explorer-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/linkedin-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/link-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/microsoft-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/openshift-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/opera-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/passport-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/paypal-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/redo-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/remove2-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/safari-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/share-alt-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/stack-overflow-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/times-circle-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/times-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/twitter-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/unlink-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/user-check-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/warning-triangle-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/yandex-international-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/index.js</include>\n+ <include>**/node_modules/@patternfly/react-styles/dist/umd/StyleSheet.js</include>\n+ <include>**/node_modules/@patternfly/react-styles/dist/umd/index.js</include>\n+ <include>**/node_modules/@patternfly/react-styles/dist/umd/utils.js</include>\n+ <include>**/node_modules/@patternfly/react-tokens/dist/umd/index.js</include>\n+ <include>**/node_modules/@tippy.js/react/dist/Tippy.min.js</include>\n+ </includes>\n+ </resource>\n</resources>\n</build>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-11293 Filter out cruft from account2 modules
339,235
21.01.2020 08:37:55
-3,600
a3e5f9d5470fa2bf4782328750c88eb1a3d54e83
Set time for admin events in milliseconds, instead of converted seconds
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/admin/AdminEventBuilder.java", "new_path": "services/src/main/java/org/keycloak/services/resources/admin/AdminEventBuilder.java", "diff": "@@ -240,7 +240,7 @@ public class AdminEventBuilder {\nif(realm.isAdminEventsDetailsEnabled()) {\nincludeRepresentation = true;\n}\n- adminEvent.setTime(Time.toMillis(Time.currentTime()));\n+ adminEvent.setTime(Time.currentTimeMillis());\nif (store != null) {\ntry {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12736 Set time for admin events in milliseconds, instead of converted seconds
339,235
21.01.2020 09:19:05
-3,600
c38baa32baeff59e15cd5e64ae882765fd1be243
Set callback URI for identity providers to use frontend URL
[ { "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": "@@ -1012,7 +1012,7 @@ module.controller('RealmIdentityProviderCtrl', function($scope, $filter, $upload\n}\n}, true);\n- $scope.callbackUrl = encodeURI($location.absUrl().replace(/\\/admin.*/, \"/realms/\") + realm.realm + \"/broker/\") ;\n+ $scope.callbackUrl = authServerUrl + \"/realms/\" + realm.realm + \"/broker/\";\n$scope.addProvider = function(provider) {\n$location.url(\"/create/identity-provider/\" + realm.realm + \"/\" + provider.id);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12685 Set callback URI for identity providers to use frontend URL
339,235
21.01.2020 10:06:12
-3,600
2916af351af8bf967d5674bf1fc36314adfb7d1f
Add thread-safety for provider hot-deployment
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/provider/ProviderManagerRegistry.java", "new_path": "services/src/main/java/org/keycloak/provider/ProviderManagerRegistry.java", "diff": "@@ -30,11 +30,11 @@ public class ProviderManagerRegistry {\nprotected List<ProviderManager> preBoot = Collections.synchronizedList(new LinkedList<>());\nprotected AtomicReference<ProviderManagerDeployer> deployerRef = new AtomicReference<>();\n- public void setDeployer(ProviderManagerDeployer deployer) {\n+ public synchronized void setDeployer(ProviderManagerDeployer deployer) {\nthis.deployerRef.set(deployer);\n}\n- public void deploy(ProviderManager pm) {\n+ public synchronized void deploy(ProviderManager pm) {\nProviderManagerDeployer deployer = getDeployer();\nif (deployer == null) {\npreBoot.add(pm);\n@@ -44,7 +44,7 @@ public class ProviderManagerRegistry {\n}\n- public void undeploy(ProviderManager pm) {\n+ public synchronized void undeploy(ProviderManager pm) {\npreBoot.remove(pm);\nProviderManagerDeployer deployer = getDeployer();\nif (deployer != null) {\n@@ -52,7 +52,7 @@ public class ProviderManagerRegistry {\n}\n}\n- public ProviderManagerDeployer getDeployer() {\n+ private ProviderManagerDeployer getDeployer() {\nreturn deployerRef.get();\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/DefaultKeycloakSessionFactory.java", "new_path": "services/src/main/java/org/keycloak/services/DefaultKeycloakSessionFactory.java", "diff": "@@ -76,6 +76,8 @@ public class DefaultKeycloakSessionFactory implements KeycloakSessionFactory, Pr\nProviderManager pm = new ProviderManager(KeycloakDeploymentInfo.create().services(), getClass().getClassLoader(), Config.scope().getArray(\"providers\"));\nspis.addAll(pm.loadSpis());\nfactoriesMap = loadFactories(pm);\n+\n+ synchronized (ProviderManagerRegistry.SINGLETON) {\nfor (ProviderManager manager : ProviderManagerRegistry.SINGLETON.getPreBoot()) {\nMap<Class<? extends Provider>, Map<String, ProviderFactory>> factoryMap = loadFactories(manager);\nfor (Map.Entry<Class<? extends Provider>, Map<String, ProviderFactory>> entry : factoryMap.entrySet()) {\n@@ -95,6 +97,8 @@ public class DefaultKeycloakSessionFactory implements KeycloakSessionFactory, Pr\n}\n// make the session factory ready for hot deployment\nProviderManagerRegistry.SINGLETON.setDeployer(this);\n+ }\n+\nAdminPermissions.registerListener(this);\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12712 Add thread-safety for provider hot-deployment
339,364
30.01.2020 12:12:06
-3,600
6eb6418208dabd767ab1d7abcbb5d16580856fbb
Fix Account Console build is missing some dependencies
[ { "change_type": "MODIFY", "old_path": "themes/pom.xml", "new_path": "themes/pom.xml", "diff": "<include>**/node_modules/@patternfly/patternfly/assets/fonts/webfonts/fa-solid-900.ttf</include>\n<include>**/node_modules/@patternfly/patternfly/assets/fonts/webfonts/fa-solid-900.woff</include>\n<include>**/node_modules/@patternfly/patternfly/assets/fonts/webfonts/fa-solid-900.ttf</include>\n+ <include>**/node_modules/@patternfly/patternfly/assets/fonts/webfonts/fa-solid-900.woff2</include>\n<include>**/node_modules/@patternfly/patternfly/assets/images/img_avatar.svg</include>\n<include>**/node_modules/@patternfly/patternfly/assets/pficon/pficon.woff2</include>\n<include>**/node_modules/@patternfly/patternfly/patternfly.min.css</include>\n<include>**/node_modules/@patternfly/react-icons/dist/umd/icons/opera-icon.js</include>\n<include>**/node_modules/@patternfly/react-icons/dist/umd/icons/passport-icon.js</include>\n<include>**/node_modules/@patternfly/react-icons/dist/umd/icons/paypal-icon.js</include>\n+ <include>**/node_modules/@patternfly/react-icons/dist/umd/icons/plus-circle-icon.js</include>\n<include>**/node_modules/@patternfly/react-icons/dist/umd/icons/redo-icon.js</include>\n<include>**/node_modules/@patternfly/react-icons/dist/umd/icons/remove2-icon.js</include>\n<include>**/node_modules/@patternfly/react-icons/dist/umd/icons/safari-icon.js</include>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12834 Fix Account Console build is missing some dependencies
339,179
09.01.2020 10:00:37
-3,600
fc7b769b6e9dd3b858dab861c52d410543d9699a
Ignore SniSSLSocketFactory exception for IBM jdk
[ { "change_type": "MODIFY", "old_path": "adapters/oidc/adapter-core/src/main/java/org/keycloak/adapters/SniSSLSocketFactory.java", "new_path": "adapters/oidc/adapter-core/src/main/java/org/keycloak/adapters/SniSSLSocketFactory.java", "diff": "@@ -23,10 +23,12 @@ import org.apache.http.conn.ssl.SSLSocketFactory;\nimport org.apache.http.conn.ssl.TrustStrategy;\nimport org.apache.http.conn.ssl.X509HostnameVerifier;\nimport org.apache.http.protocol.HttpContext;\n+import org.keycloak.common.util.Environment;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocket;\nimport java.io.IOException;\n+import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n@@ -35,9 +37,11 @@ import java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\n+import java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.security.SecureRandom;\nimport java.security.UnrecoverableKeyException;\n+import java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n@@ -46,7 +50,8 @@ import java.util.logging.Logger;\n*/\npublic class SniSSLSocketFactory extends SSLSocketFactory {\n- private static Logger log = Logger.getLogger(SniSSLSocketFactory.class.getName());\n+ private static final Logger LOG = Logger.getLogger(SniSSLSocketFactory.class.getName());\n+ private static final AtomicBoolean skipSNIApplication = new AtomicBoolean(false);\npublic SniSSLSocketFactory(String algorithm, KeyStore keystore, String keyPassword, KeyStore truststore, SecureRandom random, HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {\nsuper(algorithm, keystore, keyPassword, truststore, random, nameResolver);\n@@ -115,18 +120,35 @@ public class SniSSLSocketFactory extends SSLSocketFactory {\n}\nprivate Socket applySNI(final Socket socket, String hostname) {\n+ if (skipSNIApplication.get()) {\n+ LOG.log(Level.FINE, \"Skipping application of SNI because JDK is missing setHost() method.\");\n+ return socket;\n+ }\n+\nif (socket instanceof SSLSocket) {\ntry {\nMethod setHostMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {\n+ @Override\npublic Method run() throws NoSuchMethodException {\nreturn socket.getClass().getMethod(\"setHost\", String.class);\n}\n});\nsetHostMethod.invoke(socket, hostname);\n- log.finest(\"Applied SNI to socket for: \" + hostname);\n- } catch (Exception e) {\n- log.log(Level.WARNING, \"Failed to apply SNI to SSLSocket\", e);\n+ LOG.log(Level.FINE, \"Applied SNI to socket for host {0}\", hostname);\n+ } catch (PrivilegedActionException e) {\n+ if (e.getCause() instanceof NoSuchMethodException) {\n+ // For IBM java there is no method with name setHost(), however we don't need to applySNI\n+ // because IBM java is doing it automatically, so we can set lower level of this message\n+ // See: KEYCLOAK-6817\n+ Level logLevel = Environment.IS_IBM_JAVA ? Level.FINE : Level.WARNING;\n+ LOG.log(logLevel, \"Failed to apply SNI to SSLSocket\", e);\n+ skipSNIApplication.set(true);\n+ } else {\n+ LOG.log(Level.WARNING, \"Failed to apply SNI to SSLSocket\", e);\n+ }\n+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {\n+ LOG.log(Level.WARNING, \"Failed to apply SNI to SSLSocket\", e);\n}\n}\nreturn socket;\n" }, { "change_type": "MODIFY", "old_path": "adapters/saml/core/src/main/java/org/keycloak/adapters/cloned/SniSSLSocketFactory.java", "new_path": "adapters/saml/core/src/main/java/org/keycloak/adapters/cloned/SniSSLSocketFactory.java", "diff": "@@ -23,6 +23,7 @@ import org.apache.http.conn.ssl.SSLSocketFactory;\nimport org.apache.http.conn.ssl.TrustStrategy;\nimport org.apache.http.conn.ssl.X509HostnameVerifier;\nimport org.apache.http.protocol.HttpContext;\n+import org.keycloak.common.util.Environment;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocket;\n@@ -40,6 +41,7 @@ import java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.security.SecureRandom;\nimport java.security.UnrecoverableKeyException;\n+import java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n@@ -55,6 +57,7 @@ import java.util.logging.Logger;\npublic class SniSSLSocketFactory extends SSLSocketFactory {\nprivate static final Logger LOG = Logger.getLogger(SniSSLSocketFactory.class.getName());\n+ private static final AtomicBoolean skipSNIApplication = new AtomicBoolean(false);\npublic SniSSLSocketFactory(String algorithm, KeyStore keystore, String keyPassword, KeyStore truststore, SecureRandom random, HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {\nsuper(algorithm, keystore, keyPassword, truststore, random, nameResolver);\n@@ -123,6 +126,11 @@ public class SniSSLSocketFactory extends SSLSocketFactory {\n}\nprivate Socket applySNI(final Socket socket, String hostname) {\n+ if (skipSNIApplication.get()) {\n+ LOG.log(Level.FINE, \"Skipping application of SNI because JDK is missing setHost() method.\");\n+ return socket;\n+ }\n+\nif (socket instanceof SSLSocket) {\ntry {\nMethod setHostMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {\n@@ -133,8 +141,19 @@ public class SniSSLSocketFactory extends SSLSocketFactory {\n});\nsetHostMethod.invoke(socket, hostname);\n- LOG.log(Level.FINEST, \"Applied SNI to socket for host {0}\", hostname);\n- } catch (PrivilegedActionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {\n+ LOG.log(Level.FINE, \"Applied SNI to socket for host {0}\", hostname);\n+ } catch (PrivilegedActionException e) {\n+ if (e.getCause() instanceof NoSuchMethodException) {\n+ // For IBM java there is no method with name setHost(), however we don't need to applySNI\n+ // because IBM java is doing it automatically, so we can set lower level of this message\n+ // See: KEYCLOAK-6817\n+ Level logLevel = Environment.IS_IBM_JAVA ? Level.FINE : Level.WARNING;\n+ LOG.log(logLevel, \"Failed to apply SNI to SSLSocket\", e);\n+ skipSNIApplication.set(true);\n+ } else {\n+ LOG.log(Level.WARNING, \"Failed to apply SNI to SSLSocket\", e);\n+ }\n+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {\nLOG.log(Level.WARNING, \"Failed to apply SNI to SSLSocket\", e);\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-6817 Ignore SniSSLSocketFactory exception for IBM jdk
339,500
20.01.2020 10:03:49
-3,600
7a51ec486cbad5f0ba5eecf3a4ab8ea52345e69b
Upgrade to freemarker 2.3.29
[ { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "diff": "<dependency>\n<groupId>org.freemarker</groupId>\n<artifactId>freemarker</artifactId>\n- <version>2.3.26-incubating</version>\n+ <version>2.3.29</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://git-wip-us.apache.org/repos/asf?p=freemarker.git;a=blob_plain;f=LICENSE;hb=v2.3.26</url>\n+ <url>https://git-wip-us.apache.org/repos/asf?p=freemarker.git;a=blob_plain;f=LICENSE;hb=v2.3.29</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "RENAME", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/org.freemarker,freemarker,2.3.26-incubating,Apache Software License 2.0.txt", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/org.freemarker,freemarker,2.3.29,Apache Software License 2.0.txt", "diff": "=========================================================================\n-The Apache FreeMarker (incubating) source code contains the following\n-binaries, which were created at the Apache FreeMarker (incubating)\n-project, and hence are covered by the same license as the other source\n-files of it:\n+The source code contains the following binaries,\n+which were created at the Apache FreeMarker project, and hence are\n+covered by the same license as the other source files of it:\nsrc/main/misc/overloadedNumberRules/prices.ods\nsrc/manual/en_US/docgen-originals/figures/overview.odg\n-\n-=========================================================================\n+ src/manual/en_US/docgen-originals/figures/model2sketch_with_alpha.png\n+ src/manual/en_US/docgen-originals/figures/tree_with_alpha.png\n+ src/manual/en_US/favicon.png\n+ src/manual/en_US/figures/model2sketch.png\n+ src/manual/en_US/figures/overview.png\n+ src/manual/en_US/figures/tree.png\n+ src/manual/en_US/logo.png\n+ src/manual/zh_CN/favicon.png\n+ src/manual/zh_CN/figures/model2sketch.png\n+ src/manual/zh_CN/figures/overview.png\n+ src/manual/zh_CN/figures/tree.png\n+ src/manual/zh_CN/logo.png\n" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "diff": "<dependency>\n<groupId>org.freemarker</groupId>\n<artifactId>freemarker</artifactId>\n- <version>2.3.26.incubating-redhat-3</version>\n+ <version>2.3.29.redhat-00001</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://git-wip-us.apache.org/repos/asf?p=freemarker.git;a=blob_plain;f=LICENSE;hb=v2.3.26</url>\n+ <url>https://git-wip-us.apache.org/repos/asf?p=freemarker.git;a=blob_plain;f=LICENSE;hb=v2.3.29</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "RENAME", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/org.freemarker,freemarker,2.3.26.incubating-redhat-3,Apache Software License 2.0.txt", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/org.freemarker,freemarker,2.3.29.redhat-00001,Apache Software License 2.0.txt", "diff": "=========================================================================\n-The Apache FreeMarker (incubating) source code contains the following\n-binaries, which were created at the Apache FreeMarker (incubating)\n-project, and hence are covered by the same license as the other source\n-files of it:\n+The source code contains the following binaries,\n+which were created at the Apache FreeMarker project, and hence are\n+covered by the same license as the other source files of it:\nsrc/main/misc/overloadedNumberRules/prices.ods\nsrc/manual/en_US/docgen-originals/figures/overview.odg\n-\n-=========================================================================\n+ src/manual/en_US/docgen-originals/figures/model2sketch_with_alpha.png\n+ src/manual/en_US/docgen-originals/figures/tree_with_alpha.png\n+ src/manual/en_US/favicon.png\n+ src/manual/en_US/figures/model2sketch.png\n+ src/manual/en_US/figures/overview.png\n+ src/manual/en_US/figures/tree.png\n+ src/manual/en_US/logo.png\n+ src/manual/zh_CN/favicon.png\n+ src/manual/zh_CN/figures/model2sketch.png\n+ src/manual/zh_CN/figures/overview.png\n+ src/manual/zh_CN/figures/tree.png\n+ src/manual/zh_CN/logo.png\n" }, { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<apacheds.version>2.0.0-M21</apacheds.version>\n<apacheds.codec.version>1.0.0-M33</apacheds.codec.version>\n<google.zxing.version>3.2.1</google.zxing.version>\n- <freemarker.version>2.3.26-incubating</freemarker.version>\n+ <freemarker.version>2.3.29</freemarker.version>\n<jetty9.version>${jetty92.version}</jetty9.version>\n<liquibase.version>3.5.5</liquibase.version>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12691 Upgrade to freemarker 2.3.29
339,250
21.01.2020 15:05:53
-3,600
52fd2b4aa4ca123060fbef1eab2c30f0eec4c576
Allow setting lifespan on executeActionsEmail
[ { "change_type": "MODIFY", "old_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/UserResource.java", "new_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/UserResource.java", "diff": "@@ -185,6 +185,43 @@ public interface UserResource {\n@Path(\"execute-actions-email\")\nvoid executeActionsEmail(List<String> actions);\n+ /**\n+ * Sends an email to the user with a link within it. If they click on the link they will be asked to perform some actions\n+ * i.e. reset password, update profile, etc.\n+ *\n+ * The lifespan decides the number of seconds after which the generated token in the email link expires. The default\n+ * value is 12 hours.\n+ *\n+ * @param actions\n+ * @param lifespan\n+ */\n+ @PUT\n+ @Path(\"execute-actions-email\")\n+ void executeActionsEmail(List<String> actions, @QueryParam(\"lifespan\") Integer lifespan);\n+\n+ /**\n+ * Sends an email to the user with a link within it. If they click on the link they will be asked to perform some actions\n+ * i.e. reset password, update profile, etc.\n+ *\n+ * If redirectUri is not null, then you must specify a client id. This will set the URI you want the flow to link\n+ * to after the email link is clicked and actions completed. If both parameters are null, then no page is linked to\n+ * at the end of the flow.\n+ *\n+ * The lifespan decides the number of seconds after which the generated token in the email link expires. The default\n+ * value is 12 hours.\n+ *\n+ * @param clientId\n+ * @param redirectUri\n+ * @param lifespan\n+ * @param actions\n+ */\n+ @PUT\n+ @Path(\"execute-actions-email\")\n+ void executeActionsEmail(@QueryParam(\"client_id\") String clientId,\n+ @QueryParam(\"redirect_uri\") String redirectUri,\n+ @QueryParam(\"lifespan\") Integer lifespan,\n+ List<String> actions);\n+\n/**\n* Sends an email to the user with a link within it. If they click on the link they will be asked to perform some actions\n* i.e. reset password, update profile, etc.\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": "@@ -24,13 +24,14 @@ import org.jboss.arquillian.test.api.ArquillianResource;\nimport org.junit.Assert;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.keycloak.TokenVerifier;\nimport org.keycloak.admin.client.resource.GroupResource;\n-import org.keycloak.admin.client.resource.GroupsResource;\nimport org.keycloak.admin.client.resource.IdentityProviderResource;\nimport org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.admin.client.resource.RoleMappingResource;\nimport org.keycloak.admin.client.resource.UserResource;\nimport org.keycloak.admin.client.resource.UsersResource;\n+import org.keycloak.common.VerificationException;\nimport org.keycloak.common.util.Base64;\nimport org.keycloak.credential.CredentialModel;\nimport org.keycloak.events.admin.OperationType;\n@@ -40,6 +41,7 @@ import org.keycloak.models.PasswordPolicy;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.credential.PasswordCredentialModel;\nimport org.keycloak.models.utils.ModelToRepresentation;\n+import org.keycloak.representations.AccessToken;\nimport org.keycloak.representations.idm.ClientRepresentation;\nimport org.keycloak.representations.idm.ComponentRepresentation;\nimport org.keycloak.representations.idm.CredentialRepresentation;\n@@ -90,6 +92,7 @@ import java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n+import java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.hasSize;\n@@ -103,8 +106,6 @@ import static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.keycloak.testsuite.Assert.assertNames;\n-import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;\n-import org.keycloak.testsuite.updaters.Creator;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\n@@ -883,6 +884,66 @@ public class UserTest extends AbstractAdminTest {\nassertEquals(\"We are sorry...\", PageUtils.getPageTitle(driver));\n}\n+ @Test\n+ @AuthServerContainerExclude(AuthServer.REMOTE)\n+ public void sendResetPasswordEmailWithCustomLifespan() throws IOException {\n+ UserRepresentation userRep = new UserRepresentation();\n+ userRep.setEnabled(true);\n+ userRep.setUsername(\"user1\");\n+ userRep.setEmail(\"[email protected]\");\n+\n+ String id = createUser(userRep);\n+\n+ UserResource user = realm.users().get(id);\n+ List<String> actions = new LinkedList<>();\n+ actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name());\n+\n+ final int lifespan = (int) TimeUnit.HOURS.toSeconds(5);\n+ user.executeActionsEmail(actions, lifespan);\n+ assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + \"/execute-actions-email\", ResourceType.USER);\n+\n+ Assert.assertEquals(1, greenMail.getReceivedMessages().length);\n+\n+ MimeMessage message = greenMail.getReceivedMessages()[0];\n+\n+ MailUtils.EmailBody body = MailUtils.getBody(message);\n+\n+ assertTrue(body.getText().contains(\"Update Password\"));\n+ assertTrue(body.getText().contains(\"your Admin-client-test account\"));\n+ assertTrue(body.getText().contains(\"This link will expire within 5 hours\"));\n+\n+ assertTrue(body.getHtml().contains(\"Update Password\"));\n+ assertTrue(body.getHtml().contains(\"your Admin-client-test account\"));\n+ assertTrue(body.getHtml().contains(\"This link will expire within 5 hours\"));\n+\n+ String link = MailUtils.getPasswordResetEmailLink(body);\n+\n+ String token = link.substring(link.indexOf(\"key=\") + \"key=\".length());\n+\n+ try {\n+ final AccessToken accessToken = TokenVerifier.create(token, AccessToken.class).getToken();\n+ assertEquals(lifespan, accessToken.getExpiration() - accessToken.getIssuedAt());\n+ } catch (VerificationException e) {\n+ throw new IOException(e);\n+ }\n+\n+\n+ driver.navigate().to(link);\n+\n+ proceedPage.assertCurrent();\n+ Assert.assertThat(proceedPage.getInfo(), Matchers.containsString(\"Update Password\"));\n+ proceedPage.clickProceedLink();\n+ passwordUpdatePage.assertCurrent();\n+\n+ passwordUpdatePage.changePassword(\"new-pass\", \"new-pass\");\n+\n+ assertEquals(\"Your account has been updated.\", PageUtils.getPageTitle(driver));\n+\n+ driver.navigate().to(link);\n+\n+ assertEquals(\"We are sorry...\", PageUtils.getPageTitle(driver));\n+ }\n+\n@Test\n@AuthServerContainerExclude(AuthServer.REMOTE)\npublic void sendResetPasswordEmailSuccessTwoLinks() throws IOException {\n@@ -1194,6 +1255,91 @@ public class UserTest extends AbstractAdminTest {\nassertEquals(\"We are sorry...\", PageUtils.getPageTitle(driver));\n}\n+ @Test\n+ @AuthServerContainerExclude(AuthServer.REMOTE)\n+ public void sendResetPasswordEmailWithRedirectAndCustomLifespan() throws IOException {\n+\n+ UserRepresentation userRep = new UserRepresentation();\n+ userRep.setEnabled(true);\n+ userRep.setUsername(\"user1\");\n+ userRep.setEmail(\"[email protected]\");\n+\n+ String id = createUser(userRep);\n+\n+ UserResource user = realm.users().get(id);\n+\n+ ClientRepresentation client = new ClientRepresentation();\n+ client.setClientId(\"myclient\");\n+ client.setRedirectUris(new LinkedList<>());\n+ client.getRedirectUris().add(\"http://myclient.com/*\");\n+ client.setName(\"myclient\");\n+ client.setEnabled(true);\n+ Response response = realm.clients().create(client);\n+ String createdId = ApiUtil.getCreatedId(response);\n+ assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(createdId), client, ResourceType.CLIENT);\n+\n+\n+ List<String> actions = new LinkedList<>();\n+ actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name());\n+\n+ final int lifespan = (int) TimeUnit.DAYS.toSeconds(128);\n+\n+ try {\n+ // test that an invalid redirect uri is rejected.\n+ user.executeActionsEmail(\"myclient\", \"http://unregistered-uri.com/\", lifespan, actions);\n+ fail(\"Expected failure\");\n+ } catch (ClientErrorException e) {\n+ assertEquals(400, e.getResponse().getStatus());\n+\n+ ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);\n+ Assert.assertEquals(\"Invalid redirect uri.\", error.getErrorMessage());\n+ }\n+\n+\n+ user.executeActionsEmail(\"myclient\", \"http://myclient.com/home.html\", lifespan, actions);\n+ assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + \"/execute-actions-email\", ResourceType.USER);\n+\n+ Assert.assertEquals(1, greenMail.getReceivedMessages().length);\n+\n+ MimeMessage message = greenMail.getReceivedMessages()[0];\n+\n+ MailUtils.EmailBody body = MailUtils.getBody(message);\n+\n+ assertTrue(body.getText().contains(\"This link will expire within 128 days\"));\n+ assertTrue(body.getHtml().contains(\"This link will expire within 128 days\"));\n+\n+ String link = MailUtils.getPasswordResetEmailLink(message);\n+\n+ String token = link.substring(link.indexOf(\"key=\") + \"key=\".length());\n+\n+ try {\n+ final AccessToken accessToken = TokenVerifier.create(token, AccessToken.class).getToken();\n+ assertEquals(lifespan, accessToken.getExpiration() - accessToken.getIssuedAt());\n+ } catch (VerificationException e) {\n+ throw new IOException(e);\n+ }\n+\n+ driver.navigate().to(link);\n+\n+ proceedPage.assertCurrent();\n+ Assert.assertThat(proceedPage.getInfo(), Matchers.containsString(\"Update Password\"));\n+ proceedPage.clickProceedLink();\n+ passwordUpdatePage.assertCurrent();\n+\n+ passwordUpdatePage.changePassword(\"new-pass\", \"new-pass\");\n+\n+ assertEquals(\"Your account has been updated.\", driver.findElement(By.id(\"kc-page-title\")).getText());\n+\n+ String pageSource = driver.getPageSource();\n+\n+ // check to make sure the back link is set.\n+ Assert.assertTrue(pageSource.contains(\"http://myclient.com/home.html\"));\n+\n+ driver.navigate().to(link);\n+\n+ assertEquals(\"We are sorry...\", PageUtils.getPageTitle(driver));\n+ }\n+\n@Test\n@AuthServerContainerExclude(AuthServer.REMOTE)\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12698: Allow setting lifespan on executeActionsEmail
339,500
21.01.2020 09:30:35
-3,600
0e7b475449ad59cb5a09cbd5f12b1e19485da9e8
Upgrade to owasp-java-html-sanitizer 20191001.1
[ { "change_type": "RENAME", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/com.googlecode.owasp-java-html-sanitizer,owasp-java-html-sanitizer,20180219.1,Apache Software License 2.0.txt", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/com.googlecode.owasp-java-html-sanitizer,owasp-java-html-sanitizer,20191001.1,Apache Software License 2.0.txt", "diff": "" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "diff": "<dependency>\n<groupId>com.googlecode.owasp-java-html-sanitizer</groupId>\n<artifactId>owasp-java-html-sanitizer</artifactId>\n- <version>20180219.1</version>\n+ <version>20191001.1</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/OWASP/java-html-sanitizer/release-20180219.1/COPYING</url>\n+ <url>https://raw.githubusercontent.com/OWASP/java-html-sanitizer/release-20191001.1/COPYING</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "RENAME", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/com.googlecode.owasp-java-html-sanitizer,owasp-java-html-sanitizer,20180219.1,Apache Software License 2.0.txt", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/com.googlecode.owasp-java-html-sanitizer,owasp-java-html-sanitizer,20191001.1.0.redhat-00001,Apache Software License 2.0.txt", "diff": "" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "diff": "<dependency>\n<groupId>com.googlecode.owasp-java-html-sanitizer</groupId>\n<artifactId>owasp-java-html-sanitizer</artifactId>\n- <version>20180219.1</version>\n+ <version>20191001.1.0.redhat-00001</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/OWASP/java-html-sanitizer/release-20180219.1/COPYING</url>\n+ <url>https://raw.githubusercontent.com/OWASP/java-html-sanitizer/release-20191001.1/COPYING</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<!-- Will be used in the product. Upstream versions are overridden in the community profile -->\n<resteasy.version>3.9.3.Final</resteasy.version>\n<resteasy.undertow.version>${resteasy.version}</resteasy.undertow.version>\n- <owasp.html.sanitizer.version>20180219.1</owasp.html.sanitizer.version>\n+ <owasp.html.sanitizer.version>20191001.1</owasp.html.sanitizer.version>\n<slf4j-api.version>1.7.22</slf4j-api.version>\n<slf4j.version>1.7.22</slf4j.version>\n<sun.istack.version>3.0.7</sun.istack.version>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12694 Upgrade to owasp-java-html-sanitizer 20191001.1
339,281
20.01.2020 10:11:42
-3,600
a83467047bda5eb71e712592d50a5fbde7468ab4
KEYCLOAK-9818 Increase column size for federated foreign keys
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/resources/META-INF/jpa-changelog-9.0.0.xml", "new_path": "model/jpa/src/main/resources/META-INF/jpa-changelog-9.0.0.xml", "diff": "</addColumn>\n</changeSet>\n+ <changeSet author=\"keycloak\" id=\"9.0.0-drop-constraints-for-column-increase\">\n+ <preConditions onFail=\"MARK_RAN\" onSqlOutput=\"TEST\">\n+ <dbms type=\"mssql\"/>\n+ </preConditions>\n+\n+ <dropUniqueConstraint tableName=\"RESOURCE_SERVER_PERM_TICKET\" constraintName=\"UK_FRSR6T700S9V50BU18WS5PMT\"/>\n+ <dropUniqueConstraint tableName=\"RESOURCE_SERVER_RESOURCE\" constraintName=\"UK_FRSR6T700S9V50BU18WS5HA6\"/>\n+\n+ <dropPrimaryKey tableName=\"OFFLINE_CLIENT_SESSION\" constraintName=\"CONSTRAINT_OFFL_CL_SES_PK3\"/>\n+ </changeSet>\n+\n+ <changeSet author=\"keycloak\" id=\"9.0.0-increase-column-size-federated-fk\">\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"FED_USER_CONSENT\" columnName=\"CLIENT_ID\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"KEYCLOAK_ROLE\" columnName=\"CLIENT_REALM_CONSTRAINT\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"RESOURCE_SERVER_POLICY\" columnName=\"OWNER\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"USER_CONSENT\" columnName=\"CLIENT_ID\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"USER_ENTITY\" columnName=\"SERVICE_ACCOUNT_CLIENT_LINK\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"OFFLINE_CLIENT_SESSION\" columnName=\"CLIENT_ID\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"RESOURCE_SERVER_PERM_TICKET\" columnName=\"OWNER\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"RESOURCE_SERVER_PERM_TICKET\" columnName=\"REQUESTER\"/>\n+ <modifyDataType newDataType=\"VARCHAR(255)\" tableName=\"RESOURCE_SERVER_RESOURCE\" columnName=\"OWNER\"/>\n+ </changeSet>\n+\n+ <changeSet author=\"keycloak\" id=\"9.0.0-recreate-constraints-after-column-increase\">\n+ <preConditions onFail=\"MARK_RAN\" onSqlOutput=\"TEST\">\n+ <dbms type=\"mssql\"/>\n+ </preConditions>\n+\n+ <addNotNullConstraint columnDataType=\"VARCHAR(255)\" tableName=\"OFFLINE_CLIENT_SESSION\" columnName=\"CLIENT_ID\" />\n+ <addNotNullConstraint columnDataType=\"VARCHAR(255)\" tableName=\"RESOURCE_SERVER_PERM_TICKET\" columnName=\"OWNER\" />\n+ <addNotNullConstraint columnDataType=\"VARCHAR(255)\" tableName=\"RESOURCE_SERVER_PERM_TICKET\" columnName=\"REQUESTER\" />\n+ <addNotNullConstraint columnDataType=\"VARCHAR(255)\" tableName=\"RESOURCE_SERVER_RESOURCE\" columnName=\"OWNER\" />\n+\n+ <addUniqueConstraint tableName=\"RESOURCE_SERVER_PERM_TICKET\" columnNames=\"OWNER, REQUESTER, RESOURCE_SERVER_ID, RESOURCE_ID, SCOPE_ID\" constraintName=\"UK_FRSR6T700S9V50BU18WS5PMT\"/>\n+ <addUniqueConstraint tableName=\"RESOURCE_SERVER_RESOURCE\" columnNames=\"NAME, OWNER, RESOURCE_SERVER_ID\" constraintName=\"UK_FRSR6T700S9V50BU18WS5HA6\"/>\n+\n+ <addPrimaryKey columnNames=\"USER_SESSION_ID, CLIENT_ID, CLIENT_STORAGE_PROVIDER, EXTERNAL_CLIENT_ID, OFFLINE_FLAG\" constraintName=\"CONSTRAINT_OFFL_CL_SES_PK3\" tableName=\"OFFLINE_CLIENT_SESSION\"/>\n+ </changeSet>\n+\n</databaseChangeLog>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-9053 KEYCLOAK-9818 Increase column size for federated foreign keys
339,571
01.02.2020 13:31:54
-3,600
00a36e5f7b119ee2607b21caa15624e30009066a
Stabilize distribution profile
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/AudienceProtocolMappersTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/AudienceProtocolMappersTest.java", "diff": "@@ -36,6 +36,9 @@ import org.keycloak.representations.idm.RoleRepresentation;\nimport org.keycloak.saml.common.constants.JBossSAMLURIConstants;\nimport org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder;\nimport org.keycloak.testsuite.admin.ApiUtil;\n+import static org.keycloak.testsuite.arquillian.AuthServerTestEnricher.AUTH_SERVER_PORT;\n+import static org.keycloak.testsuite.arquillian.AuthServerTestEnricher.AUTH_SERVER_SCHEME;\n+import static org.keycloak.testsuite.arquillian.AuthServerTestEnricher.AUTH_SERVER_SSL_REQUIRED;\nimport static org.keycloak.testsuite.saml.AbstractSamlTest.REALM_NAME;\nimport static org.keycloak.testsuite.saml.AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2;\nimport static org.keycloak.testsuite.saml.RoleMapperTest.createSamlProtocolMapper;\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[KEYCLOAK-12865] Stabilize distribution profile (#6712) Signed-off-by: Jan Lieskovsky <[email protected]>
339,328
16.08.2019 16:09:03
-7,200
01a42f417fbac59204901e9c534a3622b2db1a2e
Search and Filter for the count endpoint
[ { "change_type": "MODIFY", "old_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/UsersResource.java", "new_path": "integration/admin-client/src/main/java/org/keycloak/admin/client/resource/UsersResource.java", "diff": "@@ -111,11 +111,46 @@ public interface UsersResource {\n@Consumes(MediaType.APPLICATION_JSON)\nResponse create(UserRepresentation userRepresentation);\n+ /**\n+ * Returns the number of users that can be viewed.\n+ *\n+ * @return number of users\n+ */\n@Path(\"count\")\n@GET\n@Produces(MediaType.APPLICATION_JSON)\nInteger count();\n+ /**\n+ * Returns the number of users that can be viewed and match the given search criteria.\n+ * If none is specified this is equivalent to {{@link #count()}}.\n+ *\n+ * @param search criteria to search for\n+ * @return number of users matching the search criteria\n+ */\n+ @Path(\"count\")\n+ @GET\n+ @Produces(MediaType.APPLICATION_JSON)\n+ Integer count(@QueryParam(\"search\") String search);\n+\n+ /**\n+ * Returns the number of users that can be viewed and match the given filters.\n+ * If none of the filters is specified this is equivalent to {{@link #count()}}.\n+ *\n+ * @param last last name field of a user\n+ * @param first first name field of a user\n+ * @param email email field of a user\n+ * @param username username field of a user\n+ * @return number of users matching the given filters\n+ */\n+ @Path(\"count\")\n+ @GET\n+ @Produces(MediaType.APPLICATION_JSON)\n+ Integer count(@QueryParam(\"lastName\") String last,\n+ @QueryParam(\"firstName\") String first,\n+ @QueryParam(\"email\") String email,\n+ @QueryParam(\"username\") String username);\n+\n@Path(\"{id}\")\nUserResource get(@PathParam(\"id\") String id);\n" }, { "change_type": "MODIFY", "old_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java", "new_path": "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java", "diff": "@@ -550,6 +550,31 @@ public class UserCacheSession implements UserCache {\nreturn getUsersCount(realm, false);\n}\n+ @Override\n+ public int getUsersCount(RealmModel realm, Set<String> groupIds) {\n+ return getDelegate().getUsersCount(realm, groupIds);\n+ }\n+\n+ @Override\n+ public int getUsersCount(String search, RealmModel realm) {\n+ return getDelegate().getUsersCount(search, realm);\n+ }\n+\n+ @Override\n+ public int getUsersCount(String search, RealmModel realm, Set<String> groupIds) {\n+ return getDelegate().getUsersCount(search, realm, groupIds);\n+ }\n+\n+ @Override\n+ public int getUsersCount(Map<String, String> params, RealmModel realm) {\n+ return getDelegate().getUsersCount(params, realm);\n+ }\n+\n+ @Override\n+ public int getUsersCount(Map<String, String> params, RealmModel realm, Set<String> groupIds) {\n+ return getDelegate().getUsersCount(params, realm, groupIds);\n+ }\n+\n@Override\npublic List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) {\nreturn getDelegate().getUsers(realm, firstResult, maxResults, includeServiceAccounts);\n" }, { "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": "@@ -52,6 +52,7 @@ import javax.persistence.EntityManager;\nimport javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\n+import javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;\nimport javax.persistence.criteria.Subquery;\n@@ -65,7 +66,6 @@ import java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport javax.persistence.LockModeType;\n-import javax.persistence.criteria.Expression;\n/**\n* @author <a href=\"mailto:[email protected]\">Bill Burke</a>\n@@ -607,6 +607,132 @@ public class JpaUserProvider implements UserProvider, UserCredentialStore {\nreturn getUsersCount(realm, false);\n}\n+ @Override\n+ public int getUsersCount(RealmModel realm, Set<String> groupIds) {\n+ if (groupIds == null || groupIds.isEmpty()) {\n+ return 0;\n+ }\n+\n+ TypedQuery<Long> query = em.createNamedQuery(\"userCountInGroups\", Long.class);\n+ query.setParameter(\"realmId\", realm.getId());\n+ query.setParameter(\"groupIds\", groupIds);\n+ Long count = query.getSingleResult();\n+\n+ return count.intValue();\n+ }\n+\n+ @Override\n+ public int getUsersCount(String search, RealmModel realm) {\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+\n+ return count.intValue();\n+ }\n+\n+ @Override\n+ public int getUsersCount(String search, RealmModel realm, Set<String> groupIds) {\n+ if (groupIds == null || groupIds.isEmpty()) {\n+ return 0;\n+ }\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+\n+ return count.intValue();\n+ }\n+\n+ @Override\n+ public int getUsersCount(Map<String, String> params, RealmModel realm) {\n+ CriteriaBuilder qb = em.getCriteriaBuilder();\n+ CriteriaQuery<Long> userQuery = qb.createQuery(Long.class);\n+ Root<UserEntity> from = userQuery.from(UserEntity.class);\n+ Expression<Long> count = qb.count(from);\n+\n+ userQuery = userQuery.select(count);\n+ List<Predicate> restrictions = new ArrayList<>();\n+ restrictions.add(qb.equal(from.get(\"realmId\"), realm.getId()));\n+\n+ for (Map.Entry<String, String> entry : params.entrySet()) {\n+ String key = entry.getKey();\n+ String value = entry.getValue();\n+ if (key == null || value == null) {\n+ continue;\n+ }\n+\n+ switch (key) {\n+ case UserModel.USERNAME:\n+ restrictions.add(qb.like(from.get(\"username\"), \"%\" + value + \"%\"));\n+ break;\n+ case UserModel.FIRST_NAME:\n+ restrictions.add(qb.like(from.get(\"firstName\"), \"%\" + value + \"%\"));\n+ break;\n+ case UserModel.LAST_NAME:\n+ restrictions.add(qb.like(from.get(\"lastName\"), \"%\" + value + \"%\"));\n+ break;\n+ case UserModel.EMAIL:\n+ restrictions.add(qb.like(from.get(\"email\"), \"%\" + value + \"%\"));\n+ break;\n+ }\n+ }\n+\n+ userQuery = userQuery.where(restrictions.toArray(new Predicate[0]));\n+ TypedQuery<Long> query = em.createQuery(userQuery);\n+ Long result = query.getSingleResult();\n+\n+ return result.intValue();\n+ }\n+\n+ @Override\n+ public int getUsersCount(Map<String, String> params, RealmModel realm, Set<String> groupIds) {\n+ if (groupIds == null || groupIds.isEmpty()) {\n+ return 0;\n+ }\n+\n+ CriteriaBuilder qb = em.getCriteriaBuilder();\n+ CriteriaQuery<Long> userQuery = qb.createQuery(Long.class);\n+ Root<UserGroupMembershipEntity> from = userQuery.from(UserGroupMembershipEntity.class);\n+ Expression<Long> count = qb.count(from.get(\"user\"));\n+ userQuery = userQuery.select(count);\n+\n+ List<Predicate> restrictions = new ArrayList<>();\n+ restrictions.add(qb.equal(from.get(\"user\").get(\"realmId\"), realm.getId()));\n+ restrictions.add(from.get(\"groupId\").in(groupIds));\n+\n+ for (Map.Entry<String, String> entry : params.entrySet()) {\n+ String key = entry.getKey();\n+ String value = entry.getValue();\n+ if (key == null || value == null) {\n+ continue;\n+ }\n+\n+ switch (key) {\n+ case UserModel.USERNAME:\n+ restrictions.add(qb.like(from.get(\"user\").get(\"username\"), \"%\" + value + \"%\"));\n+ break;\n+ case UserModel.FIRST_NAME:\n+ restrictions.add(qb.like(from.get(\"user\").get(\"firstName\"), \"%\" + value + \"%\"));\n+ break;\n+ case UserModel.LAST_NAME:\n+ restrictions.add(qb.like(from.get(\"user\").get(\"lastName\"), \"%\" + value + \"%\"));\n+ break;\n+ case UserModel.EMAIL:\n+ restrictions.add(qb.like(from.get(\"user\").get(\"email\"), \"%\" + value + \"%\"));\n+ break;\n+ }\n+ }\n+\n+ userQuery = userQuery.where(restrictions.toArray(new Predicate[0]));\n+ TypedQuery<Long> query = em.createQuery(userQuery);\n+ Long result = query.getSingleResult();\n+\n+ return result.intValue();\n+ }\n+\n@Override\npublic List<UserModel> getUsers(RealmModel realm) {\nreturn getUsers(realm, false);\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": "@@ -46,6 +46,8 @@ import java.util.Collection;\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=\"searchForUser\", query=\"select u from UserEntity u where u.realmId = :realmId and (u.serviceAccountClientLink is null) and \" +\n\"( lower(u.username) like :search or lower(concat(u.firstName, ' ', u.lastName)) like :search or u.email like :search ) 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(u.firstName, ' ', 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": "@@ -40,7 +40,10 @@ import java.io.Serializable;\n@NamedQuery(name=\"deleteUserGroupMembershipByRealm\", query=\"delete from UserGroupMembershipEntity mapping where mapping.user IN (select u from UserEntity u where u.realmId=:realmId)\"),\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=\"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.group.id in :groupIds\"),\n+ @NamedQuery(name=\"userCountInGroups\", query=\"select count(m.user) from UserGroupMembershipEntity m where m.user.realmId = :realmId and m.group.id in :groupIds\")\n})\n@Table(name=\"USER_GROUP_MEMBERSHIP\")\n@Entity\n" }, { "change_type": "MODIFY", "old_path": "server-spi/src/main/java/org/keycloak/storage/user/UserQueryProvider.java", "new_path": "server-spi/src/main/java/org/keycloak/storage/user/UserQueryProvider.java", "diff": "@@ -24,6 +24,8 @@ import org.keycloak.models.UserModel;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n+import java.util.Set;\n+import java.util.stream.Collectors;\n/**\n* Optional capability interface implemented by UserStorageProviders.\n@@ -43,6 +45,99 @@ public interface UserQueryProvider {\n*/\nint getUsersCount(RealmModel realm);\n+ /**\n+ * Returns the number of users that are in at least one of the groups\n+ * given.\n+ *\n+ * @param realm the realm\n+ * @param groupIds set of groups id to check for\n+ * @return the number of users that are in at least one of the groups\n+ */\n+ default int getUsersCount(RealmModel realm, Set<String> groupIds) {\n+ if (groupIds == null || groupIds.isEmpty()) {\n+ return 0;\n+ }\n+\n+ return countUsersInGroups(getUsers(realm), groupIds);\n+ }\n+\n+ /**\n+ * Returns the number of users that match the given criteria.\n+ *\n+ * @param search search criteria\n+ * @param realm the realm\n+ * @return number of users that match the search\n+ */\n+ default int getUsersCount(String search, RealmModel realm) {\n+ return searchForUser(search, realm).size();\n+ }\n+\n+ /**\n+ * Returns the number of users that match the given criteria and are in\n+ * at least one of the groups given.\n+ *\n+ * @param search search criteria\n+ * @param realm the realm\n+ * @param groupIds set of groups to check for\n+ * @return number of users that match the search and given groups\n+ */\n+ default int getUsersCount(String search, RealmModel realm, Set<String> groupIds) {\n+ if (groupIds == null || groupIds.isEmpty()) {\n+ return 0;\n+ }\n+\n+ List<UserModel> users = searchForUser(search, realm);\n+ return countUsersInGroups(users, groupIds);\n+ }\n+\n+ /**\n+ * Returns the number of users that match the given filter parameters.\n+ *\n+ * @param params filter parameters\n+ * @param realm the realm\n+ * @return number of users that match the given filters\n+ */\n+ default int getUsersCount(Map<String, String> params, RealmModel realm) {\n+ return searchForUser(params, realm).size();\n+ }\n+\n+ /**\n+ * Returns the number of users that match the given filter parameters and is in\n+ * at least one of the given groups.\n+ *\n+ * @param params filter parameters\n+ * @param realm the realm\n+ * @param groupIds set if groups to check for\n+ * @return number of users that match the given filters and groups\n+ */\n+ default int getUsersCount(Map<String, String> params, RealmModel realm, Set<String> groupIds) {\n+ if (groupIds == null || groupIds.isEmpty()) {\n+ return 0;\n+ }\n+\n+ List<UserModel> users = searchForUser(params, realm);\n+ return countUsersInGroups(users, groupIds);\n+ }\n+\n+ /**\n+ * Returns the number of users from the given list of users that are in at\n+ * least one of the groups given in the groups set.\n+ *\n+ * @param users list of users to check\n+ * @param groupIds id of groups that should be checked for\n+ * @return number of users that are in at least one of the groups\n+ */\n+ static int countUsersInGroups(List<UserModel> users, Set<String> groupIds) {\n+ return (int) users.stream().filter(u -> {\n+ for (GroupModel group : u.getGroups()) {\n+ if (groupIds.contains(group.getId())) {\n+ return true;\n+ }\n+ }\n+ return false;\n+ }).count();\n+ }\n+\n/**\n* Returns the number of users.\n*\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": "@@ -235,14 +235,73 @@ public class UsersResource {\nreturn toRepresentation(realm, userPermissionEvaluator, briefRepresentation, userModels);\n}\n+ /**\n+ * Returns the number of users that match the given criteria.\n+ * It can be called in three different ways.\n+ * 1. Don't specify any criteria and pass {@code null}. The number of all\n+ * users within that realm will be returned.\n+ * <p>\n+ * 2. If {@code search} is specified other criteria such as {@code last} will\n+ * be ignored even though you set them. The {@code search} string will be\n+ * matched against the first and last name, the username and the email of a\n+ * user.\n+ * <p>\n+ * 3. If {@code search} is unspecified but any of {@code last}, {@code first},\n+ * {@code email} or {@code username} those criteria are matched against their\n+ * respective fields on a user entity. Combined with a logical and.\n+ *\n+ * @param search arbitrary search string for all the fields below\n+ * @param last last name filter\n+ * @param first first name filter\n+ * @param email email filter\n+ * @param username username filter\n+ * @return the number of users that match the given criteria\n+ */\n@Path(\"count\")\n@GET\n@NoCache\n@Produces(MediaType.APPLICATION_JSON)\n- public Integer getUsersCount() {\n- auth.users().requireView();\n+ public Integer getUsersCount(@QueryParam(\"search\") String search,\n+ @QueryParam(\"lastName\") String last,\n+ @QueryParam(\"firstName\") String first,\n+ @QueryParam(\"email\") String email,\n+ @QueryParam(\"username\") String username) {\n+ UserPermissionEvaluator userPermissionEvaluator = auth.users();\n+ userPermissionEvaluator.requireQuery();\n+ if (search != null) {\n+ if (search.startsWith(SEARCH_ID_PARAMETER)) {\n+ UserModel userModel = session.users().getUserById(search.substring(SEARCH_ID_PARAMETER.length()).trim(), realm);\n+ return userModel != null && userPermissionEvaluator.canView(userModel) ? 1 : 0;\n+ } else if (userPermissionEvaluator.canView()) {\n+ return session.users().getUsersCount(search.trim(), realm);\n+ } else {\n+ return session.users().getUsersCount(search.trim(), realm, auth.groups().getGroupsWithViewPermission());\n+ }\n+ } else if (last != null || first != null || email != null || username != null) {\n+ Map<String, String> parameters = new HashMap<>();\n+ if (last != null) {\n+ parameters.put(UserModel.LAST_NAME, last);\n+ }\n+ if (first != null) {\n+ parameters.put(UserModel.FIRST_NAME, first);\n+ }\n+ if (email != null) {\n+ parameters.put(UserModel.EMAIL, email);\n+ }\n+ if (username != null) {\n+ parameters.put(UserModel.USERNAME, username);\n+ }\n+ if (userPermissionEvaluator.canView()) {\n+ return session.users().getUsersCount(parameters, realm);\n+ } else {\n+ return session.users().getUsersCount(parameters, realm, auth.groups().getGroupsWithViewPermission());\n+ }\n+ } else if (userPermissionEvaluator.canView()) {\nreturn session.users().getUsersCount(realm);\n+ } else {\n+ return session.users().getUsersCount(realm, auth.groups().getGroupsWithViewPermission());\n+ }\n}\nprivate List<UserRepresentation> searchForUser(Map<String, String> attributes, RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, Integer firstResult, Integer maxResults, Boolean includeServiceAccounts) {\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/storage/UserStorageManager.java", "new_path": "services/src/main/java/org/keycloak/storage/UserStorageManager.java", "diff": "@@ -462,6 +462,31 @@ public class UserStorageManager implements UserProvider, OnUserCache, OnCreateCo\nreturn getUsersCount(realm, false);\n}\n+ @Override\n+ public int getUsersCount(RealmModel realm, Set<String> groupIds) {\n+ return localStorage().getUsersCount(realm, groupIds);\n+ }\n+\n+ @Override\n+ public int getUsersCount(String search, RealmModel realm) {\n+ return localStorage().getUsersCount(search, realm);\n+ }\n+\n+ @Override\n+ public int getUsersCount(String search, RealmModel realm, Set<String> groupIds) {\n+ return localStorage().getUsersCount(search, realm, groupIds);\n+ }\n+\n+ @Override\n+ public int getUsersCount(Map<String, String> params, RealmModel realm) {\n+ return localStorage().getUsersCount(params, realm);\n+ }\n+\n+ @Override\n+ public int getUsersCount(Map<String, String> params, RealmModel realm, Set<String> groupIds) {\n+ return localStorage().getUsersCount(params, realm, groupIds);\n+ }\n+\n@FunctionalInterface\ninterface PaginatedQuery {\nList<UserModel> query(Object provider, int first, int max);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UsersTest.java", "diff": "+/*\n+ * Copyright 2019 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.testsuite.admin;\n+\n+import org.junit.Before;\n+import org.junit.Test;\n+import org.keycloak.admin.client.Keycloak;\n+import org.keycloak.admin.client.resource.AuthorizationResource;\n+import org.keycloak.admin.client.resource.RealmResource;\n+import org.keycloak.representations.idm.ClientRepresentation;\n+import org.keycloak.representations.idm.GroupRepresentation;\n+import org.keycloak.representations.idm.ManagementPermissionRepresentation;\n+import org.keycloak.representations.idm.RoleRepresentation;\n+import org.keycloak.representations.idm.UserRepresentation;\n+import org.keycloak.representations.idm.authorization.DecisionStrategy;\n+import org.keycloak.representations.idm.authorization.PolicyRepresentation;\n+import org.keycloak.representations.idm.authorization.ScopePermissionRepresentation;\n+import org.keycloak.representations.idm.authorization.UserPolicyRepresentation;\n+import org.keycloak.testsuite.util.AdminClientUtil;\n+\n+import java.io.IOException;\n+import java.security.KeyManagementException;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.cert.CertificateException;\n+import java.util.ArrayList;\n+import java.util.Collections;\n+import java.util.List;\n+import java.util.Optional;\n+\n+import static org.hamcrest.CoreMatchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class UsersTest extends AbstractAdminTest {\n+\n+ @Before\n+ public void cleanUsers() {\n+ List<UserRepresentation> userRepresentations = realm.users().list();\n+ for (UserRepresentation user : userRepresentations) {\n+ realm.users().delete(user.getId());\n+ }\n+ }\n+\n+ @Test\n+ public void countUsersWithViewPermission() {\n+ createUser(realmId, \"user1\", \"password\", \"user1FirstName\", \"user1LastName\", \"[email protected]\");\n+ createUser(realmId, \"user2\", \"password\", \"user2FirstName\", \"user2LastName\", \"[email protected]\");\n+ assertThat(realm.users().count(), is(2));\n+ }\n+\n+ @Test\n+ public 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+ }\n+\n+ @Test\n+ public void countUsersByFiltersWithViewPermission() {\n+ createUser(realmId, \"user1\", \"password\", \"user1FirstName\", \"user1LastName\", \"[email protected]\");\n+ createUser(realmId, \"user2\", \"password\", \"user2FirstName\", \"user2LastName\", \"[email protected]\");\n+ //search username\n+ assertThat(realm.users().count(null, null, null, \"user\"), is(2));\n+ assertThat(realm.users().count(null, null, null, \"user1\"), is(1));\n+ assertThat(realm.users().count(null, null, null, \"notExisting\"), is(0));\n+ assertThat(realm.users().count(null, null, null, \"\"), is(2));\n+ //search first name\n+ assertThat(realm.users().count(null, \"FirstName\", null, null), is(2));\n+ assertThat(realm.users().count(null, \"user2FirstName\", null, null), is(1));\n+ assertThat(realm.users().count(null, \"notExisting\", null, null), is(0));\n+ assertThat(realm.users().count(null, \"\", null, null), is(2));\n+ //search last name\n+ assertThat(realm.users().count(\"LastName\", null, null, null), is(2));\n+ assertThat(realm.users().count(\"user2LastName\", null, null, null), is(1));\n+ assertThat(realm.users().count(\"notExisting\", null, null, null), is(0));\n+ assertThat(realm.users().count(\"\", null, null, null), is(2));\n+ //search in email\n+ assertThat(realm.users().count(null, null, \"@example.com\", null), is(2));\n+ assertThat(realm.users().count(null, null, \"[email protected]\", null), is(1));\n+ assertThat(realm.users().count(null, null, \"[email protected]\", null), is(0));\n+ assertThat(realm.users().count(null, null, \"\", null), is(2));\n+ //search for combinations\n+ assertThat(realm.users().count(\"LastName\", \"FirstName\", null, null), is(2));\n+ assertThat(realm.users().count(\"user1LastName\", \"FirstName\", null, null), is(1));\n+ assertThat(realm.users().count(\"user1LastName\", \"\", null, null), is(1));\n+ assertThat(realm.users().count(\"LastName\", \"\", null, null), is(2));\n+ assertThat(realm.users().count(\"LastName\", \"\", null, null), is(2));\n+ assertThat(realm.users().count(null, null, \"@example.com\", \"user\"), is(2));\n+ //search not specified (defaults to simply /count)\n+ assertThat(realm.users().count(null, null, null, null), is(2));\n+ assertThat(realm.users().count(\"\", \"\", \"\", \"\"), is(2));\n+ }\n+\n+ @Test\n+ public void countUsersWithGroupViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {\n+ RealmResource testRealmResource = setupTestEnvironmentWithPermissions(true);\n+ assertThat(testRealmResource.users().count(), is(3));\n+ }\n+\n+ @Test\n+ public void countUsersBySearchWithGroupViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {\n+ RealmResource testRealmResource = setupTestEnvironmentWithPermissions(true);\n+ //search all\n+ assertThat(testRealmResource.users().count(\"user\"), is(3));\n+ //search first name\n+ assertThat(testRealmResource.users().count(\"FirstName\"), is(3));\n+ assertThat(testRealmResource.users().count(\"user2FirstName\"), is(1));\n+ //search last name\n+ assertThat(testRealmResource.users().count(\"LastName\"), is(3));\n+ assertThat(testRealmResource.users().count(\"user2LastName\"), is(1));\n+ //search in email\n+ assertThat(testRealmResource.users().count(\"@example.com\"), is(3));\n+ assertThat(testRealmResource.users().count(\"[email protected]\"), is(1));\n+ //search for something not existing\n+ assertThat(testRealmResource.users().count(\"notExisting\"), is(0));\n+ //search for empty string\n+ assertThat(testRealmResource.users().count(\"\"), is(3));\n+ //search not specified (defaults to simply /count)\n+ assertThat(testRealmResource.users().count(null), is(3));\n+ }\n+\n+ @Test\n+ public void countUsersByFiltersWithGroupViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {\n+ RealmResource testRealmResource = setupTestEnvironmentWithPermissions(true);\n+ //search username\n+ assertThat(testRealmResource.users().count(null, null, null, \"user\"), is(3));\n+ assertThat(testRealmResource.users().count(null, null, null, \"user1\"), is(1));\n+ assertThat(testRealmResource.users().count(null, null, null, \"notExisting\"), is(0));\n+ assertThat(testRealmResource.users().count(null, null, null, \"\"), is(3));\n+ //search first name\n+ assertThat(testRealmResource.users().count(null, \"FirstName\", null, null), is(3));\n+ assertThat(testRealmResource.users().count(null, \"user2FirstName\", null, null), is(1));\n+ assertThat(testRealmResource.users().count(null, \"notExisting\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(null, \"\", null, null), is(3));\n+ //search last name\n+ assertThat(testRealmResource.users().count(\"LastName\", null, null, null), is(3));\n+ assertThat(testRealmResource.users().count(\"user2LastName\", null, null, null), is(1));\n+ assertThat(testRealmResource.users().count(\"notExisting\", null, null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"\", null, null, null), is(3));\n+ //search in email\n+ assertThat(testRealmResource.users().count(null, null, \"@example.com\", null), is(3));\n+ assertThat(testRealmResource.users().count(null, null, \"[email protected]\", null), is(1));\n+ assertThat(testRealmResource.users().count(null, null, \"[email protected]\", null), is(0));\n+ assertThat(testRealmResource.users().count(null, null, \"\", null), is(3));\n+ //search for combinations\n+ assertThat(testRealmResource.users().count(\"LastName\", \"FirstName\", null, null), is(3));\n+ assertThat(testRealmResource.users().count(\"user1LastName\", \"FirstName\", null, null), is(1));\n+ assertThat(testRealmResource.users().count(\"user1LastName\", \"\", null, null), is(1));\n+ assertThat(testRealmResource.users().count(\"LastName\", \"\", null, null), is(3));\n+ assertThat(testRealmResource.users().count(\"LastName\", \"\", null, null), is(3));\n+ assertThat(testRealmResource.users().count(null, null, \"@example.com\", \"user\"), is(3));\n+ //search not specified (defaults to simply /count)\n+ assertThat(testRealmResource.users().count(null, null, null, null), is(3));\n+ assertThat(testRealmResource.users().count(\"\", \"\", \"\", \"\"), is(3));\n+ }\n+\n+ @Test\n+ public void countUsersWithNoViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {\n+ RealmResource testRealmResource = setupTestEnvironmentWithPermissions(false);\n+ assertThat(testRealmResource.users().count(), is(0));\n+ }\n+\n+ @Test\n+ public void countUsersBySearchWithNoViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {\n+ RealmResource testRealmResource = setupTestEnvironmentWithPermissions(false);\n+ //search all\n+ assertThat(testRealmResource.users().count(\"user\"), is(0));\n+ //search first name\n+ assertThat(testRealmResource.users().count(\"FirstName\"), is(0));\n+ assertThat(testRealmResource.users().count(\"user2FirstName\"), is(0));\n+ //search last name\n+ assertThat(testRealmResource.users().count(\"LastName\"), is(0));\n+ assertThat(testRealmResource.users().count(\"user2LastName\"), is(0));\n+ //search in email\n+ assertThat(testRealmResource.users().count(\"@example.com\"), is(0));\n+ assertThat(testRealmResource.users().count(\"[email protected]\"), is(0));\n+ //search for something not existing\n+ assertThat(testRealmResource.users().count(\"notExisting\"), is(0));\n+ //search for empty string\n+ assertThat(testRealmResource.users().count(\"\"), is(0));\n+ //search not specified (defaults to simply /count)\n+ assertThat(testRealmResource.users().count(null), is(0));\n+ }\n+\n+ @Test\n+ public void countUsersByFiltersWithNoViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {\n+ RealmResource testRealmResource = setupTestEnvironmentWithPermissions(false);\n+ //search username\n+ assertThat(testRealmResource.users().count(null, null, null, \"user\"), is(0));\n+ assertThat(testRealmResource.users().count(null, null, null, \"user1\"), is(0));\n+ assertThat(testRealmResource.users().count(null, null, null, \"notExisting\"), is(0));\n+ assertThat(testRealmResource.users().count(null, null, null, \"\"), is(0));\n+ //search first name\n+ assertThat(testRealmResource.users().count(null, \"FirstName\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(null, \"user2FirstName\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(null, \"notExisting\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(null, \"\", null, null), is(0));\n+ //search last name\n+ assertThat(testRealmResource.users().count(\"LastName\", null, null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"user2LastName\", null, null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"notExisting\", null, null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"\", null, null, null), is(0));\n+ //search in email\n+ assertThat(testRealmResource.users().count(null, null, \"@example.com\", null), is(0));\n+ assertThat(testRealmResource.users().count(null, null, \"[email protected]\", null), is(0));\n+ assertThat(testRealmResource.users().count(null, null, \"[email protected]\", null), is(0));\n+ assertThat(testRealmResource.users().count(null, null, \"\", null), is(0));\n+ //search for combinations\n+ assertThat(testRealmResource.users().count(\"LastName\", \"FirstName\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"user1LastName\", \"FirstName\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"user1LastName\", \"\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"LastName\", \"\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"LastName\", \"\", null, null), is(0));\n+ assertThat(testRealmResource.users().count(null, null, \"@example.com\", \"user\"), is(0));\n+ //search not specified (defaults to simply /count)\n+ assertThat(testRealmResource.users().count(null, null, null, null), is(0));\n+ assertThat(testRealmResource.users().count(\"\", \"\", \"\", \"\"), is(0));\n+ }\n+\n+ private RealmResource setupTestEnvironmentWithPermissions(boolean grp1ViewPermissions) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {\n+ String testUserId = createUser(realmId, \"test-user\", \"password\", \"\", \"\", \"\");\n+ //assign 'query-users' role to test user\n+ ClientRepresentation clientRepresentation = realm.clients().findByClientId(\"realm-management\").get(0);\n+ String realmManagementId = clientRepresentation.getId();\n+ RoleRepresentation roleRepresentation = realm.clients().get(realmManagementId).roles().get(\"query-users\").toRepresentation();\n+ realm.users().get(testUserId).roles().clientLevel(realmManagementId).add(Collections.singletonList(roleRepresentation));\n+\n+ //create test users and groups\n+ List<GroupRepresentation> groups = setupUsersInGroupsWithPermissions();\n+\n+ if (grp1ViewPermissions) {\n+ AuthorizationResource authorizationResource = realm.clients().get(realmManagementId).authorization();\n+ //create a user policy for the test user\n+ UserPolicyRepresentation policy = new UserPolicyRepresentation();\n+ String policyName = \"test-policy\";\n+ policy.setName(policyName);\n+ policy.setUsers(Collections.singleton(testUserId));\n+ authorizationResource.policies().user().create(policy);\n+ PolicyRepresentation policyRepresentation = authorizationResource.policies().findByName(policyName);\n+ //add the policy to grp1\n+ Optional<GroupRepresentation> optional = groups.stream().filter(g -> g.getName().equals(\"grp1\")).findFirst();\n+ assertThat(optional.isPresent(), is(true));\n+ GroupRepresentation grp1 = optional.get();\n+ ScopePermissionRepresentation scopePermissionRepresentation = authorizationResource.permissions().scope().findByName(\"view.members.permission.group.\" + grp1.getId());\n+ scopePermissionRepresentation.setPolicies(Collections.singleton(policyRepresentation.getId()));\n+ scopePermissionRepresentation.setDecisionStrategy(DecisionStrategy.UNANIMOUS);\n+ authorizationResource.permissions().scope().findById(scopePermissionRepresentation.getId()).update(scopePermissionRepresentation);\n+ }\n+\n+ Keycloak testUserClient = AdminClientUtil.createAdminClient(true, realm.toRepresentation().getRealm(), \"test-user\", \"password\", \"admin-cli\", \"\");\n+\n+ return testUserClient.realm(realm.toRepresentation().getRealm());\n+ }\n+\n+ private List<GroupRepresentation> setupUsersInGroupsWithPermissions() {\n+ //create two groups\n+ GroupRepresentation grp1 = createGroupWithPermissions(\"grp1\");\n+ GroupRepresentation grp2 = createGroupWithPermissions(\"grp2\");\n+ //create test users\n+ String user1Id = createUser(realmId, \"user1\", \"password\", \"user1FirstName\", \"user1LastName\", \"[email protected]\");\n+ String user2Id = createUser(realmId, \"user2\", \"password\", \"user2FirstName\", \"user2LastName\", \"[email protected]\");\n+ String user3Id = createUser(realmId, \"user3\", \"password\", \"user3FirstName\", \"user3LastName\", \"[email protected]\");\n+ String user4Id = createUser(realmId, \"user4\", \"password\", \"user4FirstName\", \"user4LastName\", \"[email protected]\");\n+ //add users to groups\n+ realm.users().get(user1Id).joinGroup(grp1.getId());\n+ realm.users().get(user2Id).joinGroup(grp1.getId());\n+ realm.users().get(user3Id).joinGroup(grp1.getId());\n+ realm.users().get(user4Id).joinGroup(grp2.getId());\n+\n+ List<GroupRepresentation> groups = new ArrayList<>();\n+ groups.add(grp1);\n+ groups.add(grp2);\n+\n+ return groups;\n+ }\n+\n+ private GroupRepresentation createGroupWithPermissions(String name) {\n+ GroupRepresentation grp = new GroupRepresentation();\n+ grp.setName(name);\n+ realm.groups().add(grp);\n+ Optional<GroupRepresentation> optional = realm.groups().groups().stream().filter(g -> g.getName().equals(name)).findFirst();\n+ assertThat(optional.isPresent(), is(true));\n+ grp = optional.get();\n+ String id = grp.getId();\n+ //enable the permissions\n+ realm.groups().group(id).setPermissions(new ManagementPermissionRepresentation(true));\n+ assertThat(realm.groups().group(id).getPermissions().isEnabled(), is(true));\n+\n+ return grp;\n+ }\n+}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
Search and Filter for the count endpoint
339,281
24.01.2020 09:41:37
-3,600
337e8f8fad5404bc5a27ea1340956861b1515747
MigrationModelTest fails in pipeline
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/MigrationModelTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/MigrationModelTest.java", "diff": "@@ -13,6 +13,7 @@ import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\nimport javax.persistence.EntityManager;\nimport java.util.List;\n+import org.jboss.logging.Logger;\nimport static org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer.REMOTE;\n@@ -40,7 +41,7 @@ public class MigrationModelTest extends AbstractKeycloakTest {\nAssert.assertEquals(currentVersion, m.getStoredVersion());\nAssert.assertEquals(m.getResourcesTag(), l.get(0).getId());\n- Time.setOffset(-5000);\n+ Time.setOffset(-60000);\nsession.realms().getMigrationModel().setStoredVersion(\"6.0.0\");\nem.flush();\n@@ -49,6 +50,9 @@ public class MigrationModelTest extends AbstractKeycloakTest {\nl = em.createQuery(\"select m from MigrationModelEntity m ORDER BY m.updatedTime DESC\", MigrationModelEntity.class).getResultList();\nAssert.assertEquals(2, l.size());\n+ Logger.getLogger(MigrationModelTest.class).info(\"MigrationModelEntity entries: \");\n+ Logger.getLogger(MigrationModelTest.class).info(\"--id: \" + l.get(0).getId() + \"; \" + l.get(0).getVersion() + \"; \" + l.get(0).getUpdateTime());\n+ Logger.getLogger(MigrationModelTest.class).info(\"--id: \" + l.get(1).getId() + \"; \" + l.get(1).getVersion() + \"; \" + l.get(1).getUpdateTime());\nAssert.assertTrue(l.get(0).getId().matches(\"[\\\\da-z]{5}\"));\nAssert.assertEquals(currentVersion, l.get(0).getVersion());\nAssert.assertTrue(l.get(1).getId().matches(\"[\\\\da-z]{5}\"));\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12240 MigrationModelTest fails in pipeline
339,500
21.01.2020 15:53:23
-3,600
441b998801ac403e032fee15ad3d56db1dfa4ec2
Upgrade to zxing 3.4.0
[ { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "diff": "<dependency>\n<groupId>com.google.zxing</groupId>\n<artifactId>core</artifactId>\n- <version>3.2.1</version>\n+ <version>3.4.0</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.2.1/COPYING</url>\n+ <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.4.0/LICENSE</url>\n</license>\n</licenses>\n</dependency>\n<dependency>\n<groupId>com.google.zxing</groupId>\n<artifactId>javase</artifactId>\n- <version>3.2.1</version>\n+ <version>3.4.0</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.2.1/COPYING</url>\n+ <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.4.0/LICENSE</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "diff": "<dependency>\n<groupId>com.google.zxing</groupId>\n<artifactId>core</artifactId>\n- <version>3.2.1.redhat-4</version>\n+ <version>3.4.0.redhat-00001</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.2.1/COPYING</url>\n+ <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.4.0/LICENSE</url>\n</license>\n</licenses>\n</dependency>\n<dependency>\n<groupId>com.google.zxing</groupId>\n<artifactId>javase</artifactId>\n- <version>3.2.1.redhat-4</version>\n+ <version>3.4.0.redhat-00001</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.2.1/COPYING</url>\n+ <url>https://raw.githubusercontent.com/zxing/zxing/zxing-3.4.0/LICENSE</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<commons-lang3.version>3.9</commons-lang3.version>\n<apacheds.version>2.0.0-M21</apacheds.version>\n<apacheds.codec.version>1.0.0-M33</apacheds.codec.version>\n- <google.zxing.version>3.2.1</google.zxing.version>\n+ <google.zxing.version>3.4.0</google.zxing.version>\n<freemarker.version>2.3.29</freemarker.version>\n<jetty9.version>${jetty92.version}</jetty9.version>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12693 Upgrade to zxing 3.4.0
339,209
31.01.2020 08:21:01
25,200
038b8fd975123583014b7ade1969081918875322
Add license information for account2 dependencies
[ { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "diff": "</license>\n</licenses>\n</other>\n+ <other>\n+ <description>Axios</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/axios/dist/axios.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/axios/axios/v0.19.0/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>ChangeCase</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/camel-case/camel-case.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/lower-case/lower-case.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/no-case.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/vendor/camel-case-regexp.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/vendor/camel-case-upper-regexp.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/vendor/non-word-regexp.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/upper-case/upper-case.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://github.com/blakeembrey/change-case/blob/v3.0.0/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Emotion</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/emotion/dist/emotion.umd.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/emotion-js/emotion/v9.2.12/packages/emotion/package.json</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>ExecutionEnvironment</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/exenv/index.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>BSD 3-clause New or Revised License</name>\n+ <url>https://raw.githubusercontent.com/JedWatson/exenv/v1.2.2/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>focus-trap-react</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/focus-trap-react/dist/focus-trap-react.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/davidtheclark/focus-trap-react/4.0.1/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>focus-trap</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/focus-trap/dist/focus-trap.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/davidtheclark/focus-trap/3.0.0/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>prop-types</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/prop-types/prop-types.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/facebook/prop-types/v15.6.2/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>React</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/react-dom/umd/react-dom.production.min.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/react-router-dom/umd/react-router-dom.min.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/react/umd/react.production.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/facebook/react/v16.8.5/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>SystemJS</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/systemjs/dist/system.src.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/systemjs/systemjs/0.20.19/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Tippy.js</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/tippy.js/dist/tippy.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/atomiks/tippyjs/v3.4.1/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Patternfly 4</description>\n+ <locations>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/patternfly</directory>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/patternfly/patternfly-next/v2.26.5/LICENSE.txt</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Patternfly 4 React</description>\n+ <locations>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-core</directory>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-icons</directory>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-styles</directory>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-tokens</directory>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://github.com/patternfly/patternfly-react/blob/master/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Tippy.js React</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/@tippy.js/react/dist/Tippy.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/atomiks/tippy.js-react/v1.1.1/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n</others>\n</licenseSummary>\n" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "diff": "</license>\n</licenses>\n</other>\n+ <other>\n+ <description>Axios</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/axios/dist/axios.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/axios/axios/v0.19.0/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>ChangeCase</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/camel-case/camel-case.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/lower-case/lower-case.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/no-case.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/vendor/camel-case-regexp.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/vendor/camel-case-upper-regexp.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/no-case/vendor/non-word-regexp.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/upper-case/upper-case.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://github.com/blakeembrey/change-case/blob/v3.0.0/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Emotion</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/emotion/dist/emotion.umd.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/emotion-js/emotion/v9.2.12/packages/emotion/package.json</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>ExecutionEnvironment</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/exenv/index.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>BSD 3-clause New or Revised License</name>\n+ <url>https://raw.githubusercontent.com/JedWatson/exenv/v1.2.2/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>focus-trap-react</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/focus-trap-react/dist/focus-trap-react.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/davidtheclark/focus-trap-react/4.0.1/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>focus-trap</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/focus-trap/dist/focus-trap.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/davidtheclark/focus-trap/3.0.0/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>prop-types</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/prop-types/prop-types.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/facebook/prop-types/v15.6.2/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>React</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/react-dom/umd/react-dom.production.min.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/react-router-dom/umd/react-router-dom.min.js</file>\n+ <file>themes/keycloak-preview/account/resources/node_modules/react/umd/react.production.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/facebook/react/v16.8.5/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>SystemJS</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/systemjs/dist/system.src.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/systemjs/systemjs/0.20.19/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Tippy.js</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/tippy.js/dist/tippy.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/atomiks/tippyjs/v3.4.1/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Patternfly 4</description>\n+ <locations>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/patternfly</directory>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/patternfly/patternfly-next/v2.26.5/LICENSE.txt</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Patternfly 4 React</description>\n+ <locations>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-core</directory>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-icons</directory>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-styles</directory>\n+ <directory>themes/keycloak-preview/account/resources/node_modules/@patternfly/react-tokens</directory>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://github.com/patternfly/patternfly-react/blob/master/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n+ <other>\n+ <description>Tippy.js React</description>\n+ <locations>\n+ <file>themes/keycloak-preview/account/resources/node_modules/@tippy.js/react/dist/Tippy.min.js</file>\n+ </locations>\n+ <licenses>\n+ <license>\n+ <name>MIT License</name>\n+ <url>https://raw.githubusercontent.com/atomiks/tippy.js-react/v1.1.1/LICENSE</url>\n+ </license>\n+ </licenses>\n+ </other>\n</others>\n</licenseSummary>\n" }, { "change_type": "MODIFY", "old_path": "themes/UPDATING-NODE-MODULES.md", "new_path": "themes/UPDATING-NODE-MODULES.md", "diff": "@@ -20,3 +20,7 @@ The node dependencies will be downloaded at build time, based on the content of\ncd -\nYou should verify the new set of packages don't break anything before commiting the new `package-lock.json`. Do not commit the `node_modules` directory for the new account console.\n+\n+## License Information\n+\n+Make sure to enter license information for new dependencies, as specified in `docs/dependency-license-information.md`. Javascript dependencies are included as `other` elements.\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12853 Add license information for account2 dependencies
339,179
30.01.2020 17:09:55
-3,600
66350f415c025d9bb2b1af308ca89039b6a48844
Exclude SameSite tests in non-SSL test runs
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/ContainerAssume.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/ContainerAssume.java", "diff": "@@ -21,6 +21,8 @@ import org.jboss.logging.Logger;\nimport org.junit.Assume;\nimport org.keycloak.testsuite.arquillian.AuthServerTestEnricher;\n+import static org.keycloak.testsuite.arquillian.AuthServerTestEnricher.AUTH_SERVER_SSL_REQUIRED;\n+\npublic class ContainerAssume {\nprivate static final Logger log = Logger.getLogger(ContainerAssume.class);\n@@ -45,4 +47,8 @@ public class ContainerAssume {\nString.format(\"Ignoring test since %s is set to false\",\nAuthServerTestEnricher.AUTH_SERVER_CLUSTER_PROPERTY), AuthServerTestEnricher.AUTH_SERVER_CLUSTER);\n}\n+\n+ public static void assumeAuthServerSSL() {\n+ Assume.assumeTrue(\"Only works with the SSL configured\", AUTH_SERVER_SSL_REQUIRED);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLSameSiteTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLSameSiteTest.java", "diff": "@@ -3,6 +3,7 @@ package org.keycloak.testsuite.adapter.servlet;\nimport org.jboss.arquillian.container.test.api.Deployment;\nimport org.jboss.arquillian.graphene.page.Page;\nimport org.jboss.shrinkwrap.api.spec.WebArchive;\n+import org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.keycloak.adapters.rotation.PublicKeyLocator;\nimport org.keycloak.testsuite.adapter.filter.AdapterActionsFilter;\n@@ -11,6 +12,7 @@ import org.keycloak.testsuite.adapter.page.EmployeeSigServlet;\nimport org.keycloak.testsuite.arquillian.annotation.AppServerContainer;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\nimport org.keycloak.testsuite.updaters.ClientAttributeUpdater;\n+import org.keycloak.testsuite.util.ContainerAssume;\nimport org.keycloak.testsuite.utils.arquillian.ContainerConstants;\nimport org.openqa.selenium.By;\n@@ -51,6 +53,11 @@ public class SAMLSameSiteTest extends AbstractSAMLServletAdapterTest {\n@Page\nprotected Employee2Servlet employee2ServletPage;\n+ @BeforeClass\n+ public static void enabledOnlyWithSSL() {\n+ ContainerAssume.assumeAuthServerSSL();\n+ }\n+\n@Test\npublic void samlWorksWithSameSiteCookieTest() throws URISyntaxException {\ngetCleanup(SAMLSERVLETDEMO).addCleanup(ClientAttributeUpdater.forClient(adminClient, SAMLSERVLETDEMO, SAML_CLIENT_ID_EMPLOYEE_2)\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java", "diff": "@@ -26,11 +26,13 @@ import org.apache.http.protocol.BasicHttpContext;\nimport org.apache.http.protocol.HttpContext;\nimport org.apache.http.util.EntityUtils;\nimport org.jboss.arquillian.graphene.page.Page;\n+import org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.auth.page.AuthRealm;\nimport org.keycloak.testsuite.pages.LoginPage;\n+import org.keycloak.testsuite.util.ContainerAssume;\nimport org.keycloak.testsuite.util.OAuthClient;\nimport org.keycloak.testsuite.util.OAuthClient.AuthorizationEndpointResponse;\nimport org.keycloak.testsuite.util.RealmBuilder;\n@@ -161,6 +163,8 @@ public class CookieTest extends AbstractKeycloakTest {\n@Test\npublic void legacyCookiesTest() {\n+ ContainerAssume.assumeAuthServerSSL();\n+\naccountPage.navigateTo();\nassertCurrentUrlStartsWithLoginUrlOf(accountPage);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookiesPathTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookiesPathTest.java", "diff": "@@ -26,6 +26,7 @@ import org.keycloak.services.managers.AuthenticationSessionManager;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.ActionURIUtils;\nimport org.keycloak.testsuite.pages.LoginPage;\n+import org.keycloak.testsuite.util.ContainerAssume;\nimport org.keycloak.testsuite.util.OAuthClient;\nimport org.keycloak.testsuite.util.RealmBuilder;\nimport org.keycloak.testsuite.util.URLUtils;\n@@ -154,6 +155,8 @@ public class CookiesPathTest extends AbstractKeycloakTest {\n@Test\npublic void testOldCookieWithWrongPath() {\n+ ContainerAssume.assumeAuthServerSSL();\n+\nCookie wrongCookie = new Cookie(AuthenticationSessionManager.AUTH_SESSION_ID, AUTH_SESSION_VALUE,\nnull, OLD_COOKIE_PATH, null, false, true);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java", "diff": "@@ -51,6 +51,7 @@ import org.keycloak.testsuite.pages.ErrorPage;\nimport org.keycloak.testsuite.pages.LoginPage;\nimport org.keycloak.testsuite.pages.LoginPasswordUpdatePage;\nimport org.keycloak.testsuite.updaters.RealmAttributeUpdater;\n+import org.keycloak.testsuite.util.ContainerAssume;\nimport org.keycloak.testsuite.util.DroneUtils;\nimport org.keycloak.testsuite.util.JavascriptBrowser;\nimport org.keycloak.testsuite.util.OAuthClient;\n@@ -416,6 +417,8 @@ public class LoginTest extends AbstractTestRealmKeycloakTest {\n@Test\npublic void loginSuccessRealmSigningAlgorithms() throws JWSInputException {\n+ ContainerAssume.assumeAuthServerSSL();\n+\nloginPage.open();\nloginPage.login(\"login-test\", \"password\");\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/javascript/AbstractJavascriptTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/javascript/AbstractJavascriptTest.java", "diff": "@@ -3,6 +3,7 @@ package org.keycloak.testsuite.javascript;\nimport org.jboss.arquillian.drone.api.annotation.Drone;\nimport org.jboss.arquillian.graphene.page.Page;\nimport org.junit.Before;\n+import org.junit.BeforeClass;\nimport org.keycloak.admin.client.resource.ClientResource;\nimport org.keycloak.representations.idm.ClientRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\n@@ -13,6 +14,7 @@ import org.keycloak.testsuite.Assert;\nimport org.keycloak.testsuite.admin.ApiUtil;\nimport org.keycloak.testsuite.auth.page.login.OIDCLogin;\nimport org.keycloak.testsuite.util.ClientBuilder;\n+import org.keycloak.testsuite.util.ContainerAssume;\nimport org.keycloak.testsuite.util.JavascriptBrowser;\nimport org.keycloak.testsuite.util.RealmBuilder;\nimport org.keycloak.testsuite.util.RolesBuilder;\n@@ -82,6 +84,10 @@ public abstract class AbstractJavascriptTest extends AbstractAuthTest {\nunauthorizedUser = UserBuilder.create().username(\"unauthorized\").password(\"password\").build();\n}\n+ @BeforeClass\n+ public static void enabledOnlyWithSSL() {\n+ ContainerAssume.assumeAuthServerSSL();\n+ }\n@Before\npublic void beforeJavascriptTest() {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12849 Exclude SameSite tests in non-SSL test runs
339,235
03.02.2020 11:32:29
-3,600
986213be235784c2cc63e69b6815918a7f7f78b8
Fix ModelVersion for testing pipeline
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/migration/ModelVersion.java", "new_path": "server-spi-private/src/main/java/org/keycloak/migration/ModelVersion.java", "diff": "@@ -25,11 +25,11 @@ import org.jboss.logging.Logger;\n*/\npublic class ModelVersion {\nprivate static Logger logger = Logger.getLogger(ModelVersion.class);\n+\nint major;\nint minor;\nint micro;\nString qualifier;\n- boolean snapshot;\npublic ModelVersion(int major, int minor, int micro) {\nthis.major = major;\n@@ -38,10 +38,7 @@ public class ModelVersion {\n}\npublic ModelVersion(String version) {\n- if (version.toUpperCase().contains(\"-SNAPSHOT\")) {\n- snapshot = true;\n- version = version.toUpperCase().split(\"-SNAPSHOT\")[0];\n- }\n+ version = version.split(\"-\")[0];\nString[] split = version.split(\"\\\\.\");\ntry {\n@@ -56,6 +53,10 @@ public class ModelVersion {\n}\nif (split.length > 3) {\nqualifier = split[3];\n+\n+ if (qualifier.startsWith(\"redhat\")) {\n+ qualifier = null;\n+ }\n}\n} catch (NumberFormatException e) {\nlogger.warn(\"failed to parse version: \" + version, e);\n@@ -78,10 +79,6 @@ public class ModelVersion {\nreturn qualifier;\n}\n- public boolean isSnapshot() {\n- return snapshot;\n- }\n-\npublic boolean lessThan(ModelVersion version) {\nif (major < version.major) {\nreturn true;\n@@ -111,10 +108,6 @@ public class ModelVersion {\nreturn false;\n}\n- if (snapshot && !version.snapshot) {\n- return true;\n- }\n-\nreturn false;\n}\n" }, { "change_type": "MODIFY", "old_path": "server-spi-private/src/test/java/org/keycloak/models/MigrationVersionTest.java", "new_path": "server-spi-private/src/test/java/org/keycloak/models/MigrationVersionTest.java", "diff": "@@ -38,7 +38,7 @@ public class MigrationVersionTest {\nAssert.assertEquals(1, version_100Beta1.getMajor());\nAssert.assertEquals(0, version_100Beta1.getMinor());\nAssert.assertEquals(0, version_100Beta1.getMicro());\n- Assert.assertTrue(version_100Beta1.isSnapshot());\n+\nModelVersion version_100CR1 = new ModelVersion(\"1.0.0.CR1\");\nModelVersion version_100 = new ModelVersion(\"1.0.0\");\nModelVersion version_110Beta1 = new ModelVersion(\"1.1.0.Beta1\");\n@@ -55,7 +55,7 @@ public class MigrationVersionTest {\nAssert.assertEquals(1, version_211CR1.getMinor());\nAssert.assertEquals(1, version_211CR1.getMicro());\nAssert.assertEquals(\"CR1\", version_211CR1.getQualifier());\n- Assert.assertFalse(version_211CR1.isSnapshot());\n+\nModelVersion version_211 = new ModelVersion(\"2.1.1\");\nModelVersion version50Snapshot = new ModelVersion(\"5.0.0-SNAPSHOT\");\n@@ -63,7 +63,6 @@ public class MigrationVersionTest {\nAssert.assertEquals(0, version50Snapshot.getMinor());\nAssert.assertEquals(0, version50Snapshot.getMicro());\nAssert.assertNull(version50Snapshot.getQualifier());\n- Assert.assertTrue(version50Snapshot.isSnapshot());\nAssert.assertFalse(version_100Beta1.lessThan(version_100Beta1));\nAssert.assertTrue(version_100Beta1.lessThan(version_100CR1));\n@@ -82,6 +81,23 @@ public class MigrationVersionTest {\nAssert.assertTrue(version_211CR1.lessThan(version50Snapshot));\n+ ModelVersion versionPipeline = new ModelVersion(\"8.0.2-REL-20200130-143126\");\n+ Assert.assertEquals(8, versionPipeline.getMajor());\n+ Assert.assertEquals(0, versionPipeline.getMinor());\n+ Assert.assertEquals(2, versionPipeline.getMicro());\n+ Assert.assertNull(versionPipeline.getQualifier());\n+\n+ ModelVersion versionPipeline2 = new ModelVersion(\"9.1.2-SNAPSHOT-stage-20191125-003440\");\n+ Assert.assertEquals(9, versionPipeline2.getMajor());\n+ Assert.assertEquals(1, versionPipeline2.getMinor());\n+ Assert.assertEquals(2, versionPipeline2.getMicro());\n+ Assert.assertNull(versionPipeline2.getQualifier());\n+\n+ ModelVersion versionProduct = new ModelVersion(\"7.0.0.redhat-00002\");\n+ Assert.assertEquals(7, versionProduct.getMajor());\n+ Assert.assertEquals(0, versionProduct.getMinor());\n+ Assert.assertEquals(0, versionProduct.getMicro());\n+ Assert.assertNull(versionProduct.getQualifier());\n}\n@Test\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12877 Fix ModelVersion for testing pipeline
339,500
21.01.2020 10:08:09
-3,600
73eaa38357ab9d90aea45075fe8b5bbb68a2fdf8
Upgrade to twitter4j 4.0.7
[ { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "diff": "<dependency>\n<groupId>org.twitter4j</groupId>\n<artifactId>twitter4j-core</artifactId>\n- <version>4.0.4</version>\n+ <version>4.0.7</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/yusuke/twitter4j/4.0.4/LICENSE.txt</url>\n+ <url>https://raw.githubusercontent.com/yusuke/twitter4j/4.0.7/LICENSE.txt</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "RENAME", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/org.twitter4j,twitter4j-core,4.0.4,Apache Software License 2.0.txt", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/org.twitter4j,twitter4j-core,4.0.7,Apache Software License 2.0.txt", "diff": "incurred by, or claims asserted against, such Contributor by reason\nof your accepting any such warranty or additional liability.\n-Twitter4J SUBCOMPONENTS:\n-Twitter4J includes software from JSON.org to parse JSON response from the Twitter API. You can see the license term at http://www.JSON.org/license.html\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "diff": "<dependency>\n<groupId>org.twitter4j</groupId>\n<artifactId>twitter4j-core</artifactId>\n- <version>4.0.4.redhat-3</version>\n+ <version>4.0.7.redhat-00002</version>\n<licenses>\n<license>\n<name>Apache Software License 2.0</name>\n- <url>https://raw.githubusercontent.com/yusuke/twitter4j/4.0.4/LICENSE.txt</url>\n+ <url>https://raw.githubusercontent.com/yusuke/twitter4j/4.0.7/LICENSE.txt</url>\n</license>\n</licenses>\n</dependency>\n" }, { "change_type": "RENAME", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/org.twitter4j,twitter4j-core,4.0.4.redhat-3,Apache Software License 2.0.txt", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/org.twitter4j,twitter4j-core,4.0.7.redhat-00002,Apache Software License 2.0.txt", "diff": "incurred by, or claims asserted against, such Contributor by reason\nof your accepting any such warranty or additional liability.\n-Twitter4J SUBCOMPONENTS:\n-Twitter4J includes software from JSON.org to parse JSON response from the Twitter API. You can see the license term at http://www.JSON.org/license.html\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<mssql.version>7.4.1.jre8</mssql.version>\n<servlet.api.30.version>1.0.2.Final</servlet.api.30.version>\n<servlet.api.40.version>1.0.0.Final</servlet.api.40.version>\n- <twitter4j.version>4.0.4</twitter4j.version>\n+ <twitter4j.version>4.0.7</twitter4j.version>\n<jna.version>4.1.0</jna.version>\n<!-- Test -->\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12692 Upgrade to twitter4j 4.0.7
339,138
03.02.2020 16:22:43
-10,800
b6c5acef25905b9009ee9694d9a38de7d1894b3d
SAML users should not be identified by SAML:NameID
[ { "change_type": "MODIFY", "old_path": "saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/constants/X500SAMLProfileConstants.java", "new_path": "saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/constants/X500SAMLProfileConstants.java", "diff": "*/\npackage org.keycloak.saml.processing.core.saml.v2.constants;\n+import org.keycloak.dom.saml.v2.assertion.AttributeType;\n+\nimport java.util.EnumSet;\nimport java.util.HashMap;\nimport java.util.Map;\n+import java.util.Objects;\n/**\n* X500 SAML Profile Constants Adapted from\n@@ -147,6 +150,12 @@ public enum X500SAMLProfileConstants {\nreturn friendlyName;\n}\n+ public boolean correspondsTo(AttributeType attribute) {\n+ return attribute != null\n+ ? Objects.equals(this.uri, attribute.getName()) || Objects.equals(this.friendlyName, attribute.getFriendlyName())\n+ : false;\n+ }\n+\npublic static String getOID(final String key) {\nreturn lookup.get(key);\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/broker/saml/SAMLEndpoint.java", "new_path": "services/src/main/java/org/keycloak/broker/saml/SAMLEndpoint.java", "diff": "@@ -85,7 +85,9 @@ import java.security.Key;\nimport java.security.cert.X509Certificate;\nimport java.util.LinkedList;\nimport java.util.List;\n+import java.util.function.Predicate;\n+import org.keycloak.protocol.saml.SamlPrincipalType;\nimport org.keycloak.rotation.HardcodedKeyLocator;\nimport org.keycloak.rotation.KeyLocator;\nimport org.keycloak.saml.processing.core.util.KeycloakKeySamlExtensionGenerator;\n@@ -414,15 +416,24 @@ public class SAMLEndpoint {\nSubjectType subject = assertion.getSubject();\nSubjectType.STSubType subType = subject.getSubType();\nNameIDType subjectNameID = (NameIDType) subType.getBaseID();\n+ String principal = getPrincipal(assertion);\n+\n+ if (principal == null) {\n+ logger.errorf(\"no principal in assertion; expected: %s\", expectedPrincipalType());\n+ event.event(EventType.IDENTITY_PROVIDER_RESPONSE);\n+ event.error(Errors.INVALID_SAML_RESPONSE);\n+ return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUESTER);\n+ }\n+\n//Map<String, String> notes = new HashMap<>();\n- BrokeredIdentityContext identity = new BrokeredIdentityContext(subjectNameID.getValue());\n+ BrokeredIdentityContext identity = new BrokeredIdentityContext(principal);\nidentity.getContextData().put(SAML_LOGIN_RESPONSE, responseType);\nidentity.getContextData().put(SAML_ASSERTION, assertion);\nif (clientId != null && ! clientId.trim().isEmpty()) {\nidentity.getContextData().put(SAML_IDP_INITIATED_CLIENT_ID, clientId);\n}\n- identity.setUsername(subjectNameID.getValue());\n+ identity.setUsername(principal);\n//SAML Spec 2.2.2 Format is optional\nif (subjectNameID.getFormat() != null && subjectNameID.getFormat().toString().equals(JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.get())) {\n@@ -461,19 +472,12 @@ public class SAMLEndpoint {\n}\n}\nif (assertion.getAttributeStatements() != null ) {\n- for (AttributeStatementType attrStatement : assertion.getAttributeStatements()) {\n- for (AttributeStatementType.ASTChoiceType choice : attrStatement.getAttributes()) {\n- AttributeType attribute = choice.getAttribute();\n- if (X500SAMLProfileConstants.EMAIL.getFriendlyName().equals(attribute.getFriendlyName())\n- || X500SAMLProfileConstants.EMAIL.get().equals(attribute.getName())) {\n- if (!attribute.getAttributeValue().isEmpty()) identity.setEmail(attribute.getAttributeValue().get(0).toString());\n- }\n- }\n-\n+ String email = getX500Attribute(assertion, X500SAMLProfileConstants.EMAIL);\n+ if (email != null)\n+ identity.setEmail(email);\n}\n- }\n- String brokerUserId = config.getAlias() + \".\" + subjectNameID.getValue();\n+ String brokerUserId = config.getAlias() + \".\" + principal;\nidentity.setBrokerUserId(brokerUserId);\nidentity.setIdpConfig(config);\nidentity.setIdp(provider);\n@@ -632,4 +636,59 @@ public class SAMLEndpoint {\n}\n+ private String getX500Attribute(AssertionType assertion, X500SAMLProfileConstants attribute) {\n+ return getFirstMatchingAttribute(assertion, attribute::correspondsTo);\n+ }\n+\n+ private String getAttributeByName(AssertionType assertion, String name) {\n+ return getFirstMatchingAttribute(assertion, attribute -> Objects.equals(attribute.getName(), name));\n+ }\n+\n+ private String getAttributeByFriendlyName(AssertionType assertion, String friendlyName) {\n+ return getFirstMatchingAttribute(assertion, attribute -> Objects.equals(attribute.getFriendlyName(), friendlyName));\n+ }\n+\n+ private String getPrincipal(AssertionType assertion) {\n+\n+ SamlPrincipalType principalType = config.getPrincipalType();\n+\n+ if (principalType == null || principalType.equals(SamlPrincipalType.SUBJECT)) {\n+ SubjectType subject = assertion.getSubject();\n+ SubjectType.STSubType subType = subject.getSubType();\n+ NameIDType subjectNameID = (NameIDType) subType.getBaseID();\n+ return subjectNameID.getValue();\n+ } else if (principalType.equals(SamlPrincipalType.ATTRIBUTE)) {\n+ return getAttributeByName(assertion, config.getPrincipalAttribute());\n+ } else {\n+ return getAttributeByFriendlyName(assertion, config.getPrincipalAttribute());\n+ }\n+\n+ }\n+\n+ private String getFirstMatchingAttribute(AssertionType assertion, Predicate<AttributeType> predicate) {\n+ return assertion.getAttributeStatements().stream()\n+ .map(AttributeStatementType::getAttributes)\n+ .flatMap(Collection::stream)\n+ .map(AttributeStatementType.ASTChoiceType::getAttribute)\n+ .filter(predicate)\n+ .map(AttributeType::getAttributeValue)\n+ .flatMap(Collection::stream)\n+ .findFirst()\n+ .map(Object::toString)\n+ .orElse(null);\n+ }\n+\n+ private String expectedPrincipalType() {\n+ SamlPrincipalType principalType = config.getPrincipalType();\n+ switch (principalType) {\n+ case SUBJECT:\n+ return principalType.name();\n+ case ATTRIBUTE:\n+ case FRIENDLY_ATTRIBUTE:\n+ return String.format(\"%s(%s)\", principalType.name(), config.getPrincipalAttribute());\n+ default:\n+ return null;\n+ }\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/broker/saml/SAMLIdentityProviderConfig.java", "new_path": "services/src/main/java/org/keycloak/broker/saml/SAMLIdentityProviderConfig.java", "diff": "@@ -18,6 +18,7 @@ package org.keycloak.broker.saml;\nimport org.keycloak.models.IdentityProviderModel;\n+import org.keycloak.protocol.saml.SamlPrincipalType;\nimport org.keycloak.saml.common.util.XmlKeyInfoKeyNameTransformer;\n/**\n@@ -40,6 +41,8 @@ public class SAMLIdentityProviderConfig extends IdentityProviderModel {\npublic static final String SINGLE_LOGOUT_SERVICE_URL = \"singleLogoutServiceUrl\";\npublic static final String SINGLE_SIGN_ON_SERVICE_URL = \"singleSignOnServiceUrl\";\npublic static final String VALIDATE_SIGNATURE = \"validateSignature\";\n+ public static final String PRINCIPAL_TYPE = \"principalType\";\n+ public static final String PRINCIPAL_ATTRIBUTE = \"principalAttribute\";\npublic static final String WANT_ASSERTIONS_ENCRYPTED = \"wantAssertionsEncrypted\";\npublic static final String WANT_ASSERTIONS_SIGNED = \"wantAssertionsSigned\";\npublic static final String WANT_AUTHN_REQUESTS_SIGNED = \"wantAuthnRequestsSigned\";\n@@ -253,4 +256,24 @@ public class SAMLIdentityProviderConfig extends IdentityProviderModel {\ngetConfig().put(ALLOWED_CLOCK_SKEW, String.valueOf(allowedClockSkew));\n}\n}\n+\n+ public SamlPrincipalType getPrincipalType() {\n+ return SamlPrincipalType.from(getConfig().get(PRINCIPAL_TYPE), SamlPrincipalType.SUBJECT);\n+ }\n+\n+ public void setPrincipalType(SamlPrincipalType principalType) {\n+ getConfig().put(PRINCIPAL_TYPE,\n+ principalType == null\n+ ? null\n+ : principalType.name());\n+ }\n+\n+ public String getPrincipalAttribute() {\n+ return getConfig().get(PRINCIPAL_ATTRIBUTE);\n+ }\n+\n+ public void setPrincipalAttribute(String principalAttribute) {\n+ getConfig().put(PRINCIPAL_ATTRIBUTE, principalAttribute);\n+ }\n+\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "services/src/main/java/org/keycloak/protocol/saml/SamlPrincipalType.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.protocol.saml;\n+\n+public enum SamlPrincipalType {\n+\n+ SUBJECT,\n+ ATTRIBUTE,\n+ FRIENDLY_ATTRIBUTE;\n+\n+ public static SamlPrincipalType from(String name, SamlPrincipalType defaultValue) {\n+ if (name == null) {\n+ return defaultValue;\n+ }\n+ try {\n+ return valueOf(name);\n+ } catch (IllegalArgumentException ex) {\n+ return defaultValue;\n+ }\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlIdPInitiatedSsoTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlIdPInitiatedSsoTest.java", "diff": "package org.keycloak.testsuite.broker;\nimport org.keycloak.admin.client.resource.ClientsResource;\n+import org.keycloak.admin.client.resource.IdentityProviderResource;\nimport org.keycloak.admin.client.resource.UsersResource;\n+import org.keycloak.broker.saml.SAMLIdentityProviderConfig;\nimport org.keycloak.common.util.StreamUtil;\nimport org.keycloak.common.util.StringPropertyReplacer;\nimport org.keycloak.dom.saml.v2.assertion.AssertionType;\n+import org.keycloak.dom.saml.v2.assertion.AttributeStatementType;\n+import org.keycloak.dom.saml.v2.assertion.AttributeType;\nimport org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType;\n+import org.keycloak.dom.saml.v2.assertion.StatementAbstractType;\nimport org.keycloak.dom.saml.v2.protocol.ResponseType;\n+import org.keycloak.protocol.saml.SamlPrincipalType;\nimport org.keycloak.representations.idm.ClientRepresentation;\n+import org.keycloak.representations.idm.FederatedIdentityRepresentation;\n+import org.keycloak.representations.idm.IdentityProviderRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.representations.idm.UserRepresentation;\nimport org.keycloak.representations.idm.UserSessionRepresentation;\nimport org.keycloak.saml.common.constants.JBossSAMLURIConstants;\nimport org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder;\n+import org.keycloak.saml.processing.core.saml.v2.constants.X500SAMLProfileConstants;\nimport org.keycloak.saml.processing.core.saml.v2.util.AssertionUtil;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.Assert;\n@@ -109,6 +118,14 @@ public class KcSamlIdPInitiatedSsoTest extends AbstractKeycloakTest {\nurlRealmConsumer2 = getAuthRoot() + \"/auth/realms/\" + REALM_CONS_NAME + \"-2\";\n}\n+ @Before\n+ public void resetPrincipalType() {\n+ IdentityProviderResource idp = adminClient.realm(REALM_CONS_NAME).identityProviders().get(\"saml-leaf\");\n+ IdentityProviderRepresentation rep = idp.toRepresentation();\n+ rep.getConfig().put(SAMLIdentityProviderConfig.PRINCIPAL_TYPE, SamlPrincipalType.SUBJECT.name());\n+ idp.update(rep);\n+ }\n+\n@Override\npublic void addTestRealms(List<RealmRepresentation> testRealms) {\ninitRealmUrls();\n@@ -324,6 +341,62 @@ public class KcSamlIdPInitiatedSsoTest extends AbstractKeycloakTest {\n);\n}\n+ // KEYCLOAK-7969\n+ @Test\n+ public void testProviderIdpInitiatedLoginWithPrincipalAttribute() throws Exception {\n+ IdentityProviderResource idp = adminClient.realm(REALM_CONS_NAME).identityProviders().get(\"saml-leaf\");\n+ IdentityProviderRepresentation rep = idp.toRepresentation();\n+ rep.getConfig().put(SAMLIdentityProviderConfig.PRINCIPAL_TYPE, SamlPrincipalType.ATTRIBUTE.name());\n+ rep.getConfig().put(SAMLIdentityProviderConfig.PRINCIPAL_ATTRIBUTE, X500SAMLProfileConstants.UID.get());\n+ idp.update(rep);\n+\n+ SAMLDocumentHolder samlResponse = new SamlClientBuilder()\n+ .navigateTo(getSamlIdpInitiatedUrl(REALM_PROV_NAME, \"samlbroker\"))\n+ // Login in provider realm\n+ .login().user(PROVIDER_REALM_USER_NAME, PROVIDER_REALM_USER_PASSWORD).build()\n+\n+ // Send the response to the consumer realm\n+ .processSamlResponse(Binding.POST)\n+ .transformObject(ob -> {\n+ assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));\n+ ResponseType resp = (ResponseType) ob;\n+ assertThat(resp.getDestination(), is(getSamlBrokerIdpInitiatedUrl(REALM_CONS_NAME, \"sales\")));\n+ assertAudience(resp, getSamlBrokerIdpInitiatedUrl(REALM_CONS_NAME, \"sales\"));\n+\n+ Set<StatementAbstractType> statements = resp.getAssertions().get(0).getAssertion().getStatements();\n+\n+ AttributeStatementType attributeType = (AttributeStatementType) statements.stream()\n+ .filter(statement -> statement instanceof AttributeStatementType)\n+ .findFirst().orElse(new AttributeStatementType());\n+\n+ AttributeType attr = new AttributeType(X500SAMLProfileConstants.UID.get());\n+ attr.addAttributeValue(PROVIDER_REALM_USER_NAME);\n+\n+ attributeType.addAttribute(new AttributeStatementType.ASTChoiceType(attr));\n+ resp.getAssertions().get(0).getAssertion().addStatement(attributeType);\n+\n+ return ob;\n+ })\n+ .build()\n+\n+ .updateProfile().username(CONSUMER_CHOSEN_USERNAME).email(\"test@localhost\").firstName(\"Firstname\").lastName(\"Lastname\").build()\n+ .followOneRedirect()\n+\n+ // Obtain the response sent to the app\n+ .getSamlResponse(Binding.POST);\n+\n+ assertThat(samlResponse.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));\n+ ResponseType resp = (ResponseType) samlResponse.getSamlObject();\n+ assertThat(resp.getDestination(), is(urlRealmConsumer + \"/app/auth\"));\n+ assertAudience(resp, urlRealmConsumer + \"/app/auth\");\n+\n+ UsersResource users = adminClient.realm(REALM_CONS_NAME).users();\n+ String id = users.search(CONSUMER_CHOSEN_USERNAME).get(0).getId();\n+ FederatedIdentityRepresentation fed = users.get(id).getFederatedIdentity().get(0);\n+ assertThat(fed.getUserId(), is(PROVIDER_REALM_USER_NAME));\n+ assertThat(fed.getUserName(), is(PROVIDER_REALM_USER_NAME));\n+ }\n+\nprivate void assertSingleUserSession(String realmName, String userName, String... expectedClientIds) {\nfinal UsersResource users = adminClient.realm(realmName).users();\nfinal ClientsResource clients = adminClient.realm(realmName).clients();\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": "@@ -643,6 +643,10 @@ single-logout-service-url=Single Logout Service URL\nsaml.single-logout-service-url.tooltip=The Url that must be used to send logout requests.\nnameid-policy-format=NameID Policy Format\nnameid-policy-format.tooltip=Specifies the URI reference corresponding to a name identifier format. Defaults to urn:oasis:names:tc:SAML:2.0:nameid-format:persistent.\n+saml.principal-type=Principal Type\n+saml.principal-type.tooltip=Way to identify and track external users from the assertion. Default is using Subject NameID, alternatively you can set up identifying attribute.\n+saml.principal-attribute=Principal Attribute\n+saml.principal-attribute.tooltip=Name or Friendly Name of the attribute used to identify external users.\nhttp-post-binding-response=HTTP-POST Binding Response\nhttp-post-binding-response.tooltip=Indicates whether to respond to requests using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used.\nhttp-post-binding-for-authn-request=HTTP-POST Binding for AuthnRequest\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": "@@ -834,10 +834,28 @@ module.controller('RealmIdentityProviderCtrl', function($scope, $filter, $upload\n\"KEY_ID\",\n\"CERT_SUBJECT\"\n];\n+ $scope.principalTypes = [\n+ {\n+ type: \"SUBJECT\",\n+ name: \"Subject NameID\"\n+\n+ },\n+ {\n+ type: \"ATTRIBUTE\",\n+ name: \"Attribute [Name]\"\n+\n+ },\n+ {\n+ type: \"FRIENDLY_ATTRIBUTE\",\n+ name: \"Attribute [Friendly Name]\"\n+\n+ }\n+ ];\nif (instance && instance.alias) {\n} else {\n$scope.identityProvider.config.nameIDPolicyFormat = $scope.nameIdFormats[0].format;\n+ $scope.identityProvider.config.principalType = $scope.principalTypes[0].type;\n$scope.identityProvider.config.signatureAlgorithm = $scope.signatureAlgorithms[1];\n$scope.identityProvider.config.samlXmlKeyNameTranformer = $scope.xmlKeyNameTranformers[1];\n}\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/admin/resources/partials/realm-identity-provider-saml.html", "new_path": "themes/src/main/resources/theme/base/admin/resources/partials/realm-identity-provider-saml.html", "diff": "</div>\n<kc-tooltip>{{:: 'nameid-policy-format.tooltip' | translate}}</kc-tooltip>\n</div>\n+ <div class=\"form-group clearfix\">\n+ <label class=\"col-md-2 control-label\" for=\"principalType\">{{:: 'saml.principal-type' | translate}}</label>\n+ <div class=\"col-md-6\">\n+ <select id=\"principalType\" ng-model=\"identityProvider.config.principalType\"\n+ ng-options=\"pType.type as pType.name for pType in principalTypes\">\n+ </select>\n+ </div>\n+ <kc-tooltip>{{:: 'saml.principal-type.tooltip' | translate}}</kc-tooltip>\n+ </div>\n+ <div class=\"form-group clearfix\" data-ng-show=\"identityProvider.config.principalType.endsWith('ATTRIBUTE')\">\n+ <label class=\"col-md-2 control-label\" for=\"principalAttribute\">{{:: 'saml.principal-attribute' | translate}}</label>\n+ <div class=\"col-md-6\">\n+ <input class=\"form-control\" id=\"principalAttribute\" type=\"text\" ng-model=\"identityProvider.config.principalAttribute\" ng-required=\"identityProvider.config.principalType.endsWith('ATTRIBUTE')\">\n+ </div>\n+ <kc-tooltip>{{:: 'saml.principal-attribute.tooltip' | translate}}</kc-tooltip>\n+ </div>\n<div class=\"form-group\">\n<label class=\"col-md-2 control-label\" for=\"postBindingResponse\">{{:: 'http-post-binding-response' | translate}}</label>\n<div class=\"col-md-6\">\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-7969 - SAML users should not be identified by SAML:NameID
339,235
06.02.2020 09:41:04
-3,600
32fccfa99e9957bc23c2a43f56c7bf9ff65c5d40
Fix lower-case column names in IdentityProviderMapperEntity, while they are upper-case in Liquibase scripts
[ { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/IdentityProviderMapperEntity.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/IdentityProviderMapperEntity.java", "diff": "@@ -53,8 +53,8 @@ public class IdentityProviderMapperEntity {\nprotected String identityProviderMapper;\n@ElementCollection\n- @MapKeyColumn(name=\"name\")\n- @Column(name=\"value\")\n+ @MapKeyColumn(name=\"NAME\")\n+ @Column(name=\"VALUE\")\n@CollectionTable(name=\"IDP_MAPPER_CONFIG\", joinColumns={ @JoinColumn(name=\"IDP_MAPPER_ID\") })\nprivate Map<String, String> config;\n" }, { "change_type": "MODIFY", "old_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserFederationProviderEntity.java", "new_path": "model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserFederationProviderEntity.java", "diff": "@@ -54,7 +54,7 @@ public class UserFederationProviderEntity {\nprivate int priority;\n@ElementCollection\n- @MapKeyColumn(name=\"name\")\n+ @MapKeyColumn(name=\"NAME\")\n@Column(name=\"VALUE\")\n@CollectionTable(name=\"USER_FEDERATION_CONFIG\", joinColumns={ @JoinColumn(name=\"USER_FEDERATION_PROVIDER_ID\") })\nprivate Map<String, String> config;\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-10391 Fix lower-case column names in IdentityProviderMapperEntity, while they are upper-case in Liquibase scripts
339,581
06.02.2020 15:30:44
-3,600
a506115a93391517fe4869cb49116829d28785a5
DatasetLoader in performance swallows exceptions
[ { "change_type": "MODIFY", "old_path": "testsuite/performance/tests/src/main/java/org/keycloak/performance/dataset/Creatable.java", "new_path": "testsuite/performance/tests/src/main/java/org/keycloak/performance/dataset/Creatable.java", "diff": "@@ -2,6 +2,7 @@ package org.keycloak.performance.dataset;\nimport java.io.IOException;\nimport javax.ws.rs.ClientErrorException;\n+import javax.ws.rs.WebApplicationException;\nimport javax.ws.rs.core.Response;\nimport static org.keycloak.admin.client.CreatedResponseUtil.getCreatedId;\nimport org.keycloak.admin.client.Keycloak;\n@@ -32,7 +33,7 @@ public interface Creatable<REP> extends Updatable<REP> {\npublic Response create(Keycloak adminClient);\npublic default boolean createCheckingForConflict(Keycloak adminClient) {\n- logger().trace(\"creating \" + this);\n+ logger().debug(\"Creating \" + this);\nboolean conflict = false;\ntry {\nResponse response = create(adminClient);\n@@ -41,23 +42,26 @@ public interface Creatable<REP> extends Updatable<REP> {\n} else {\nString responseBody = response.readEntity(String.class);\nresponse.close();\n- if (response.getStatus() == 409) { // some endpoints dont't throw exception on 409, throwing here\n- throw new ClientErrorException(HTTP_409_SUFFIX, response);\n- }\n+ switch (response.getStatus()) {\n+ case 201: // created\nif (responseBody != null && !responseBody.isEmpty()) {\n- logger().trace(responseBody);\n+ logger().trace(String.format(\"Response status: %s, body: %s\", response.getStatus(), responseBody));\nsetRepresentation(EntityTemplate.OBJECT_MAPPER.readValue(responseBody, (Class<REP>) getRepresentation().getClass()));\n} else {\nsetId(getCreatedId(response));\n}\n+ break;\n+ case 409: // some client endpoints dont't throw exception on 409 response, throwing from here\n+ throw new ClientErrorException(HTTP_409_SUFFIX, response);\n+ default:\n+ throw new RuntimeException(String.format(\"Error when creating entity %s.\", this), new WebApplicationException(response));\n+ }\n}\n} catch (ClientErrorException ex) {\nif (ex.getResponse().getStatus() == 409) {\nconflict = true;\n- logger().trace(\"entity already exists\");\n+ logger().debug(String.format(\"Entity %s already exists.\", this));\nreadAndSetId(adminClient);\n- } else {\n- throw ex;\n}\n} catch (IOException ex) {\nthrow new RuntimeException(ex);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/performance/tests/src/main/java/org/keycloak/performance/dataset/DatasetLoader.java", "new_path": "testsuite/performance/tests/src/main/java/org/keycloak/performance/dataset/DatasetLoader.java", "diff": "package org.keycloak.performance.dataset;\n+import java.io.PrintWriter;\n+import java.io.StringWriter;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\n@@ -28,7 +30,7 @@ public class DatasetLoader implements Loggable {\nprivate static final int QUEUE_TIMEOUT = Integer.parseInt(System.getProperty(\"queue.timeout\", \"60\"));\nprivate static final int THREADPOOL_SHUTDOWN_TIMEOUT = Integer.parseInt(System.getProperty(\"shutdown.timeout\", \"60\"));\n- public static void main(String[] args) {\n+ public static void main(String[] args) throws InterruptedException {\nDatasetTemplate template = new DatasetTemplate();\ntemplate.validateConfiguration();\nDatasetLoader loader = new DatasetLoader(template.produce(), DELETE);\n@@ -49,6 +51,7 @@ public class DatasetLoader implements Loggable {\nValidate.notNull(dataset);\nthis.dataset = dataset;\nthis.delete = delete;\n+ logger().info(String.format(\"Opening %s admin clients.\", TestConfig.numOfWorkers));\nfor (int i = 0; i < TestConfig.numOfWorkers; i++) {\nadminClients.add(Keycloak.getInstance(\nTestConfig.serverUrisIterator.next(),\n@@ -59,7 +62,7 @@ public class DatasetLoader implements Loggable {\n}\n}\n- private void processDataset() {\n+ private void processDataset() throws InterruptedException {\nif (delete) {\nlogger().info(\"Deleting dataset.\");\nprocessEntities(dataset.realms());\n@@ -92,9 +95,10 @@ public class DatasetLoader implements Loggable {\n}\n}\n- private void processEntities(Stream<? extends Updatable> stream) {\n+ private void processEntities(Stream<? extends Updatable> stream) throws InterruptedException {\nif (!errorReported()) {\nIterator<? extends Updatable> iterator = stream.iterator();\n+ logger().debug(\"Creating thread pool.\");\nExecutorService threadPool = Executors.newFixedThreadPool(TestConfig.numOfWorkers);\nBlockingQueue<Updatable> queue = new LinkedBlockingQueue<>(TestConfig.numOfWorkers + 5);\ntry {\n@@ -103,12 +107,10 @@ public class DatasetLoader implements Loggable {\ntry {\nif (queue.offer(iterator.next(), QUEUE_TIMEOUT, SECONDS)) {\nthreadPool.execute(() -> {\n- if (!errorReported()) {\ntry {\n-\nUpdatable updatable = queue.take();\n+ if (!errorReported()) {\nKeycloak adminClient = adminClients.take();\n-\ntry {\nif (delete) {\n@@ -126,10 +128,9 @@ public class DatasetLoader implements Loggable {\n} finally {\nadminClients.add(adminClient); // return client for reuse\n}\n-\n- } catch (Exception ex) {\n- reportError(ex);\n}\n+ } catch (Throwable ex) {\n+ reportError(ex);\n}\n});\n} else {\n@@ -142,21 +143,18 @@ public class DatasetLoader implements Loggable {\n} catch (Exception ex) {\nreportError(ex);\n}\n- // shut down threadpool\n- if (errorReported()) {\n- logger().error(\"Exception thrown from executor service. Shutting down.\");\n- threadPool.shutdownNow();\n- throw new RuntimeException(error);\n- } else {\n- try {\n+\n+ logger().debug(\"Terminating thread pool.\");\nthreadPool.shutdown();\nthreadPool.awaitTermination(THREADPOOL_SHUTDOWN_TIMEOUT, SECONDS);\nif (!threadPool.isTerminated()) {\n- throw new IllegalStateException(\"Executor service still not terminated.\");\n- }\n- } catch (InterruptedException ex) {\n- throw new RuntimeException(ex);\n+ logger().error(\"Failed to terminate the thread pool. Attempting force shutdown.\");\n+ threadPool.shutdownNow();\n}\n+\n+ if (errorReported()) {\n+ closeAdminClients();\n+ throw new Error(error);\n}\n}\n}\n@@ -192,11 +190,16 @@ public class DatasetLoader implements Loggable {\nprivate synchronized void reportError(Throwable ex) {\nlogProcessedEntityCounts(true);\n- logger().error(\"Error occured: \" + ex);\n+\n+ StringWriter sw = new StringWriter();\n+ ex.printStackTrace(new PrintWriter(sw));\n+\n+ logger().error(String.format(\"Error occured in thread %s: %s\", Thread.currentThread().getName(), sw.toString()));\nthis.error = ex;\n}\npublic void closeAdminClients() {\n+ logger().info(\"Closing admin clients.\");\nwhile (!adminClients.isEmpty()) {\nadminClients.poll().close();\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/performance/tests/src/main/resources/logback.xml", "new_path": "testsuite/performance/tests/src/main/resources/logback.xml", "diff": "<appender-ref ref=\"CONSOLE_MSG_ONLY\" />\n</logger>\n+ <!--logging for dataset-->\n+ <logger name=\"org.keycloak.performance.dataset\" level=\"INFO\" additivity=\"false\">\n+ <appender-ref ref=\"CONSOLE_MSG_ONLY\" />\n+ </logger>\n<logger name=\"ch.qos.logback\" level=\"WARN\"/>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12838 DatasetLoader in performance swallows exceptions (#6708)
339,167
06.02.2020 10:35:11
-3,600
27f6f7bf40e71e4c794286ef5d93c4edfe8ee285
Impossible to compile keycloak examples
[ { "change_type": "MODIFY", "old_path": "examples/providers/authenticator/README.md", "new_path": "examples/providers/authenticator/README.md", "diff": "Example Custom Authenticator\n===================================================\n-1. First, Keycloak must be running.\n+1. First, Keycloak must be running. See [Getting Started](https://github.com/keycloak/keycloak#getting-started), or you\n+ can build distribution from [source](https://github.com/keycloak/keycloak/blob/master/docs/building.md).\n2. Execute the follow. This will build the example and deploy it\n- $ mvn clean install wildfly:deploy\n+ `$ mvn clean install wildfly:deploy`\n-3. Copy the secret-question.ftl and secret-question-config.ftl files to the themes/base/login directory.\n+3. Copy the `secret-question.ftl` and `secret-question-config.ftl` files to the `themes/base/login` server directory.\n4. Login to admin console. Hit browser refresh if you are already logged in so that the new providers show up.\n-5. Go to the Authentication menu item and go to the Flow tab, you will be able to view the currently\n+5. Go to the **Authentication** menu item and go to the **Flows** tab, you will be able to view the currently\ndefined flows. You cannot modify an built in flows, so, to add the Authenticator you\nhave to copy an existing flow or create your own. Copy the \"Browser\" flow.\n-6. In your copy, click the \"Actions\" menu item and \"Add Execution\". Pick Secret Question\n+6. In your copy, click the **Actions** menu item in **Forms** subflow and **Add Execution**. Pick `Secret Question` and change\n+ the **Requirement** choice.\n-7. Next you have to register the required action that you created. Click on the Required Actions tab in the Authentication menu.\n- Click on the Register button and choose your new Required Action.\n+7. Go to the **Bindings** tab in **Authentication** menu and change the default **Browser Flow** to your copy of the browser flow\n+ and click `Save`.\n+\n+8. Next you have to register the required action that you created. Click on the **Required Actions** tab in the **Authentication** menu.\n+ Click on the `Register` button and choose your new Required Action. You can also choose the `Default Action` for the Required Action\n+ and each new user has to set the secret answer.\nYour new required action should now be displayed and enabled in the required actions list.\n" }, { "change_type": "MODIFY", "old_path": "examples/providers/authenticator/secret-question.ftl", "new_path": "examples/providers/authenticator/secret-question.ftl", "diff": "-<#import \"select.ftl\" as layout>\n+<#import \"template.ftl\" as layout>\n<@layout.registrationLayout; section>\n<#if section = \"title\">\n${msg(\"loginTitle\",realm.name)}\n" }, { "change_type": "MODIFY", "old_path": "examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionAuthenticator.java", "new_path": "examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionAuthenticator.java", "diff": "@@ -98,7 +98,7 @@ public class SecretQuestionAuthenticator implements Authenticator, CredentialVal\npublic void addCookie(AuthenticationFlowContext context, String name, String value, String path, String domain, String comment, int maxAge, boolean secure, boolean httpOnly) {\nHttpResponse response = context.getSession().getContext().getContextObject(HttpResponse.class);\nStringBuffer cookieBuf = new StringBuffer();\n- ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, comment, maxAge, secure, httpOnly);\n+ ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, comment, maxAge, secure, httpOnly, null);\nString cookie = cookieBuf.toString();\nresponse.getOutputHeaders().add(HttpHeaders.SET_COOKIE, cookie);\n}\n@@ -107,11 +107,10 @@ public class SecretQuestionAuthenticator implements Authenticator, CredentialVal\nprotected boolean validateAnswer(AuthenticationFlowContext context) {\nMultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();\nString secret = formData.getFirst(\"secret_answer\");\n- String credentialId = context.getSelectedCredentialId();\n+ String credentialId = formData.getFirst(\"credentialId\");\nif (credentialId == null || credentialId.isEmpty()) {\ncredentialId = getCredentialProvider(context.getSession())\n.getDefaultCredential(context.getSession(), context.getRealm(), context.getUser()).getId();\n- context.setSelectedCredentialId(credentialId);\n}\nUserCredentialModel input = new UserCredentialModel(credentialId, getType(context.getSession()), secret);\n" }, { "change_type": "MODIFY", "old_path": "examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProvider.java", "new_path": "examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProvider.java", "diff": "@@ -22,6 +22,7 @@ import org.keycloak.credential.CredentialInput;\nimport org.keycloak.credential.CredentialInputValidator;\nimport org.keycloak.credential.CredentialModel;\nimport org.keycloak.credential.CredentialProvider;\n+import org.keycloak.credential.CredentialTypeMetadata;\nimport org.keycloak.credential.UserCredentialStore;\nimport org.keycloak.examples.authenticator.credential.SecretQuestionCredentialModel;\nimport org.keycloak.models.KeycloakSession;\n@@ -94,6 +95,18 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr\nreturn SecretQuestionCredentialModel.createFromCredentialModel(model);\n}\n+ @Override\n+ public CredentialTypeMetadata getCredentialTypeMetadata() {\n+ return CredentialTypeMetadata.builder()\n+ .type(getType())\n+ .category(CredentialTypeMetadata.Category.TWO_FACTOR)\n+ .displayName(SecretQuestionCredentialProviderFactory.PROVIDER_ID)\n+ .helpText(\"secret-question-text\")\n+ .createAction(SecretQuestionAuthenticatorFactory.PROVIDER_ID)\n+ .removeable(false)\n+ .build(session);\n+ }\n+\n@Override\npublic String getType() {\nreturn SecretQuestionCredentialModel.TYPE;\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12910 Impossible to compile keycloak examples
339,235
07.02.2020 11:43:29
-3,600
5d1fa8719e12c7013c2016621efe1cf8bdeb0a00
Fix PartialImportTest for client validation
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/partialimport/PartialImportTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/partialimport/PartialImportTest.java", "diff": "@@ -139,7 +139,7 @@ public class PartialImportTest extends AbstractAuthTest {\nClientRepresentation client = new ClientRepresentation();\nclient.setClientId(CLIENT_SERVICE_ACCOUNT);\nclient.setName(CLIENT_SERVICE_ACCOUNT);\n- client.setRootUrl(\"foo\");\n+ client.setRootUrl(\"http://localhost/foo\");\nclient.setProtocol(\"openid-connect\");\nclient.setPublicClient(false);\nclient.setSecret(\"secret\");\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12190 Fix PartialImportTest for client validation
339,179
06.02.2020 09:58:10
-3,600
3f29c27e16fd6a9cf438e7e6a887058252fab78e
Describe how to run testsuite against openshift
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/HOW-TO-RUN.md", "new_path": "testsuite/integration-arquillian/HOW-TO-RUN.md", "diff": "@@ -147,6 +147,32 @@ run other/adapters/jboss/remote tests:\n-Dauth.server.ssl.required=false \\\n-Dapp.server.ssl.required=false\n+### Running tests against container not produced by the testsuite\n+\n+For running the testsuite, it is necessary to install/deploy so-called testsuite-providers. The testsuite rely on\n+testsuite-providers in many test scenarios for example for checking fired events, moving in time etc. When using\n+keycloak from `integration-arquillian-servers-auth-server-wildfly-*.zip`, it should not be necessary to do any steps\n+because testsuite-providers are already included in this archive. However, when a clean keycloak is used, e.g.\n+openshift image, testsuite-providers jar file is deployed to the container in the beginning of test run.\n+To be able to deploy the jar to the container, arquillian has to have an access to the management port.\n+\n+For example, to run testsuite against image in openshift, we need to first forward 9990 port from the running pod.\n+```shell script\n+oc port-forward \"${POD}\" 9990:9990\n+```\n+where ${POD} is a name of the pod\n+\n+Now just run testsuite against the image in openshift:\n+```shell script\n+mvn clean install -f testsuite/integration-arquillian/tests/base/pom.xml \\\n+ -Pauth-server-remote \\\n+ -Dauth.server.ssl.required=false \\\n+ -Dauth.server.host=\"${HOST}\" \\\n+ -Dauth.server.http.port=80 \\\n+ -Dauth.server.management.host=127.0.0.1 \\\n+ -Dauth.server.management.port=9990\n+```\n+where ${HOST} is url of keycloak, for example: `keycloak-keycloak.192.168.42.91.nip.io`.\n## Run adapter tests\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12906 Describe how to run testsuite against openshift
339,167
07.02.2020 11:49:07
-3,600
a5d02d62c148e88d5dcc426eb0fdfffa5fe78ada
TOTP not accepted in request for Access token
[ { "change_type": "MODIFY", "old_path": "core/src/main/java/org/keycloak/OAuth2Constants.java", "new_path": "core/src/main/java/org/keycloak/OAuth2Constants.java", "diff": "@@ -55,6 +55,8 @@ public interface OAuth2Constants {\nString IMPLICIT = \"implicit\";\n+ String USERNAME=\"username\";\n+\nString PASSWORD = \"password\";\nString CLIENT_CREDENTIALS = \"client_credentials\";\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidateOTP.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidateOTP.java", "diff": "@@ -60,6 +60,9 @@ public class ValidateOTP extends AbstractDirectGrantAuthenticator implements Cre\nString otp = inputData.getFirst(\"otp\");\n+ // KEYCLOAK-12908 Backwards compatibility. If paramter \"otp\" is null, then assign \"totp\".\n+ otp = (otp == null) ? inputData.getFirst(\"totp\") : otp;\n+\n// Always use default OTP credential in case of direct grant authentication\nString credentialId = getCredentialProvider(context.getSession())\n.getDefaultCredential(context.getSession(), context.getRealm(), context.getUser()).getId();\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java", "diff": "@@ -21,7 +21,9 @@ import org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.keycloak.OAuth2Constants;\nimport org.keycloak.events.Details;\n+import org.keycloak.models.Constants;\nimport org.keycloak.models.utils.TimeBasedOTP;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.representations.idm.UserRepresentation;\n@@ -32,11 +34,21 @@ import org.keycloak.testsuite.pages.AppPage.RequestType;\nimport org.keycloak.testsuite.pages.LoginPage;\nimport org.keycloak.testsuite.pages.LoginTotpPage;\nimport org.keycloak.testsuite.util.GreenMailRule;\n+import org.keycloak.testsuite.util.OAuthClient;\nimport org.keycloak.testsuite.util.RealmRepUtil;\nimport org.keycloak.testsuite.util.UserBuilder;\n+import javax.ws.rs.client.Client;\n+import javax.ws.rs.client.ClientBuilder;\n+import javax.ws.rs.client.Entity;\n+import javax.ws.rs.client.WebTarget;\n+import javax.ws.rs.core.Form;\n+import javax.ws.rs.core.Response;\n+import java.io.IOException;\nimport java.net.MalformedURLException;\n+import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;\n+\n/**\n* @author <a href=\"mailto:[email protected]\">Stian Thorgersen</a>\n* @author Stan Silvert [email protected] (C) 2016 Red Hat Inc.\n@@ -182,4 +194,38 @@ public class LoginTotpTest extends AbstractTestRealmKeycloakTest {\nloginPage.assertCurrent();\n}\n+\n+ //KEYCLOAK-12908\n+ @Test\n+ public void loginWithTotp_getToken_checkCompatibilityCLI() throws IOException {\n+ Client httpClient = ClientBuilder.newClient();\n+ try {\n+ WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT)\n+ .path(\"/realms\")\n+ .path(TEST)\n+ .path(\"protocol/openid-connect/token\");\n+\n+ Form form = new Form()\n+ .param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)\n+ .param(OAuth2Constants.USERNAME, \"test-user@localhost\")\n+ .param(OAuth2Constants.PASSWORD, \"password\")\n+ .param(OAuth2Constants.CLIENT_ID, Constants.ADMIN_CLI_CLIENT_ID);\n+\n+ // Compatibility between \"otp\" and \"totp\"\n+ Response response = exchangeUrl.request()\n+ .post(Entity.form(form.param(\"otp\", totp.generateTOTP(\"totpSecret\"))));\n+\n+ Assert.assertEquals(200, response.getStatus());\n+ response.close();\n+\n+ response = exchangeUrl.request()\n+ .post(Entity.form(form.param(\"totp\", totp.generateTOTP(\"totpSecret\"))));\n+\n+ Assert.assertEquals(200, response.getStatus());\n+ response.close();\n+\n+ } finally {\n+ httpClient.close();\n+ }\n+ }\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12908 TOTP not accepted in request for Access token
339,235
13.12.2019 05:25:20
-3,600
ecec20ad597ae360a964b4c039827bab8e27a2fe
Internal error message returned in error response
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/error/KeycloakErrorHandler.java", "new_path": "services/src/main/java/org/keycloak/services/error/KeycloakErrorHandler.java", "diff": "package org.keycloak.services.error;\n+import com.fasterxml.jackson.core.JsonParseException;\nimport org.jboss.logging.Logger;\nimport org.jboss.resteasy.spi.Failure;\nimport org.jboss.resteasy.spi.HttpResponse;\n@@ -106,17 +107,18 @@ public class KeycloakErrorHandler implements ExceptionMapper<Throwable> {\nFailure f = (Failure) throwable;\nstatus = f.getErrorCode();\n}\n+ if (throwable instanceof JsonParseException) {\n+ status = Response.Status.BAD_REQUEST.getStatusCode();\n+ }\nreturn status;\n}\nprivate String getErrorCode(Throwable throwable) {\n- String error = throwable.getMessage();\n-\n- if (error == null) {\n- return \"unknown_error\";\n+ if (throwable instanceof WebApplicationException && throwable.getMessage() != null) {\n+ return throwable.getMessage();\n}\n- return error;\n+ return \"unknown_error\";\n}\nprivate RealmModel resolveRealm() {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/error/UncaughtErrorPageTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/error/UncaughtErrorPageTest.java", "diff": "package org.keycloak.testsuite.error;\n+import org.apache.commons.io.IOUtils;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpPost;\n+import org.apache.http.client.methods.HttpRequestBase;\n+import org.apache.http.entity.StringEntity;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.impl.client.HttpClientBuilder;\nimport org.jboss.arquillian.graphene.page.Page;\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.keycloak.admin.client.resource.RealmResource;\n+import org.keycloak.broker.provider.util.SimpleHttp;\nimport org.keycloak.common.util.StreamUtil;\n+import org.keycloak.representations.idm.ErrorRepresentation;\n+import org.keycloak.representations.idm.OAuth2ErrorRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected;\nimport org.keycloak.testsuite.pages.ErrorPage;\n+import org.keycloak.util.JsonSerialization;\nimport javax.ws.rs.core.Response;\n-\nimport java.io.IOException;\nimport java.io.InputStream;\n-import java.lang.reflect.Array;\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.nio.charset.Charset;\nimport java.util.Collections;\nimport java.util.List;\n-import static org.junit.Assert.assertEquals;\n-import static org.junit.Assert.assertNull;\n-import static org.junit.Assert.assertTrue;\n+import static org.junit.Assert.*;\npublic class UncaughtErrorPageTest extends AbstractKeycloakTest {\n@@ -61,6 +68,43 @@ public class UncaughtErrorPageTest extends AbstractKeycloakTest {\nAssert.assertTrue(responseString.contains(\"An internal server error has occurred\"));\n}\n+ @Test\n+ @UncaughtServerErrorExpected\n+ public void uncaughtErrorClientRegistration() throws IOException {\n+ try (CloseableHttpClient client = HttpClientBuilder.create().build()) {\n+ HttpPost post = new HttpPost(suiteContext.getAuthServerInfo().getUriBuilder().path(\"/auth/realms/master/clients-registrations/openid-connect\").build());\n+ post.setEntity(new StringEntity(\"{ invalid : invalid }\"));\n+ post.setHeader(\"Content-Type\", \"application/json\");\n+\n+ CloseableHttpResponse response = client.execute(post);\n+ assertEquals(400, response.getStatusLine().getStatusCode());\n+\n+ OAuth2ErrorRepresentation error = JsonSerialization.readValue(response.getEntity().getContent(), OAuth2ErrorRepresentation.class);\n+ assertEquals(\"unknown_error\", error.getError());\n+ assertNull(error.getErrorDescription());\n+ }\n+ }\n+\n+ @Test\n+ @UncaughtServerErrorExpected\n+ public void uncaughtErrorAdmin() throws IOException {\n+ try (CloseableHttpClient client = HttpClientBuilder.create().build()) {\n+ String accessToken = adminClient.tokenManager().getAccessTokenString();\n+\n+ HttpPost post = new HttpPost(suiteContext.getAuthServerInfo().getUriBuilder().path(\"/auth/admin/realms\").build());\n+ post.setEntity(new StringEntity(\"{ invalid : invalid }\"));\n+ post.setHeader(\"Authorization\", \"bearer \" + accessToken);\n+ post.setHeader(\"Content-Type\", \"application/json\");\n+\n+ CloseableHttpResponse response = client.execute(post);\n+ assertEquals(400, response.getStatusLine().getStatusCode());\n+\n+ OAuth2ErrorRepresentation error = JsonSerialization.readValue(response.getEntity().getContent(), OAuth2ErrorRepresentation.class);\n+ assertEquals(\"unknown_error\", error.getError());\n+ assertNull(error.getErrorDescription());\n+ }\n+ }\n+\n@Test\n@UncaughtServerErrorExpected\npublic void uncaughtError() throws MalformedURLException {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12193 Internal error message returned in error response
339,179
22.01.2020 12:57:02
-3,600
e5935d8069154db2bc9ee83ae85c7e1ff6822324
Fix shrinkwrap issue by updating arquillian bom version
[ { "change_type": "MODIFY", "old_path": "docs/building.md", "new_path": "docs/building.md", "diff": "## Building from source\n-Ensure you have JDK 8 (or newer), Maven 3.1.1 (or newer) and Git installed\n+Ensure you have JDK 8 (or newer), Maven 3.5.4 (or newer) and Git installed\njava -version\nmvn -version\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/pom.xml", "new_path": "testsuite/integration-arquillian/pom.xml", "diff": "<wildfly.deprecated.arquillian.wildfly.container>2.1.1.Final</wildfly.deprecated.arquillian.wildfly.container>\n<!--component versions-->\n- <!--\n- to update arquillian-core to 1.3.0.Final or higher\n- - see https://issues.jboss.org/browse/ARQ-2181\n- - update org.keycloak.testsuite.arquillian.containers.KeycloakContainerTestExtension according to\n- current version of org.jboss.arquillian.container.test.impl.ContainerTestExtension\n- -->\n- <arquillian-core.version>1.2.1.Final</arquillian-core.version>\n+ <arquillian-core.version>1.6.0.Final</arquillian-core.version>\n<!--the version of shrinkwrap_resolver should align with the version in arquillian-bom-->\n- <shrinkwrap-resolver.version>2.2.6</shrinkwrap-resolver.version>\n+ <shrinkwrap-resolver.version>3.1.4</shrinkwrap-resolver.version>\n<selenium.version>3.14.0</selenium.version>\n<arquillian-drone.version>2.5.1</arquillian-drone.version>\n<arquillian-graphene.version>2.3.2</arquillian-graphene.version>\n</execution>\n</executions>\n</plugin>\n+ <plugin>\n+ <groupId>org.apache.maven.plugins</groupId>\n+ <artifactId>maven-enforcer-plugin</artifactId>\n+ <version>${version.enforcer.plugin}</version>\n+ <executions>\n+ <execution>\n+ <id>enforce-maven</id>\n+ <goals>\n+ <goal>enforce</goal>\n+ </goals>\n+ <configuration>\n+ <rules>\n+ <requireMavenVersion>\n+ <version>3.5.4</version>\n+ </requireMavenVersion>\n+ </rules>\n+ </configuration>\n+ </execution>\n+ </executions>\n+ </plugin>\n</plugins>\n</build>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/pom.xml", "new_path": "testsuite/integration-arquillian/tests/base/pom.xml", "diff": "<artifactId>mvel2</artifactId>\n<version>${mvel.version}</version>\n</dependency>\n+ <dependency>\n+ <groupId>org.apache.maven.resolver</groupId>\n+ <artifactId>maven-resolver-api</artifactId>\n+ </dependency>\n</dependencies>\n<build>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/util/pom.xml", "new_path": "testsuite/integration-arquillian/util/pom.xml", "diff": "<groupId>org.jboss.arquillian.container</groupId>\n<artifactId>arquillian-container-karaf-managed</artifactId>\n</dependency>\n+ <dependency>\n+ <groupId>org.apache.maven.resolver</groupId>\n+ <artifactId>maven-resolver-api</artifactId>\n+ </dependency>\n+\n<dependency>\n<groupId>org.jboss.arquillian.container</groupId>\n<artifactId>arquillian-container-osgi</artifactId>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/performance/README.md", "new_path": "testsuite/performance/README.md", "diff": "## Requirements:\n- Bash 2.05+\n-- Maven 3.1.1+\n+- Maven 3.5.4+\n- Keycloak server distribution installed in the local Maven repository. To do this run `mvn install -Pdistribution` from the root of the Keycloak project.\n### Docker Compose Provisioner\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12764 Fix shrinkwrap issue by updating arquillian bom version
339,179
04.02.2020 17:22:14
-3,600
62c9e1577618470832ede22dcedd46cba15b1836
Remove Request parameters from exception message
[ { "change_type": "MODIFY", "old_path": "authz/client/src/main/java/org/keycloak/authorization/client/util/HttpMethod.java", "new_path": "authz/client/src/main/java/org/keycloak/authorization/client/util/HttpMethod.java", "diff": "@@ -103,7 +103,7 @@ public class HttpMethod<R> {\n} catch (HttpResponseException e) {\nthrow e;\n} catch (Exception e) {\n- throw new RuntimeException(\"Error executing http method [\" + builder + \"]. Response : \" + String.valueOf(bytes), e);\n+ throw new RuntimeException(\"Error executing http method [\" + builder.getMethod() + \"]. Response : \" + String.valueOf(bytes), e);\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12638 Remove Request parameters from exception message
339,209
10.02.2020 07:21:32
25,200
3ef338d392cb9a32a8d96375fff489f37446677a
Filter out git-Logo.svg to fix zip for Windows Should be safe to filter, upstream PR redhat-rcue/rcue#89 will remove eventually, and tests use lowercase version of this file.
[ { "change_type": "MODIFY", "old_path": "themes/pom.xml", "new_path": "themes/pom.xml", "diff": "<exclude>**/Gruntfile.js</exclude>\n<exclude>**/Gemfile*</exclude>\n<exclude>**/.*</exclude>\n+ <!-- Remove once rcue stops shipping this file -->\n+ <exclude>**/git-Logo.svg</exclude>\n<!-- Remove once account2 manual filter list is removed -->\n<exclude>**/keycloak-preview/account/resources/node_modules/**</exclude>\n</excludes>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-9436 Filter out git-Logo.svg to fix zip for Windows Should be safe to filter, upstream PR redhat-rcue/rcue#89 will remove eventually, and tests use lowercase version of this file.
339,500
15.01.2020 08:59:50
-3,600
1d54f2ade391f397956fdcb66f75daf0182d8c1e
Improve access token checks for userinfo endpoint
[ { "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": "@@ -22,8 +22,10 @@ import org.jboss.resteasy.spi.HttpRequest;\nimport org.keycloak.OAuth2Constants;\nimport org.keycloak.OAuthErrorException;\nimport org.keycloak.TokenCategory;\n+import org.keycloak.TokenVerifier;\nimport org.keycloak.cluster.ClusterProvider;\nimport org.keycloak.common.ClientConnection;\n+import org.keycloak.common.VerificationException;\nimport org.keycloak.common.util.Time;\nimport org.keycloak.crypto.HashProvider;\nimport org.keycloak.crypto.SignatureProvider;\n@@ -56,6 +58,7 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType;\nimport org.keycloak.representations.AccessToken;\nimport org.keycloak.representations.AccessTokenResponse;\nimport org.keycloak.representations.IDToken;\n+import org.keycloak.representations.JsonWebToken;\nimport org.keycloak.representations.RefreshToken;\nimport org.keycloak.services.ErrorResponseException;\nimport org.keycloak.services.managers.AuthenticationManager;\n@@ -161,17 +164,14 @@ public class TokenManager {\nthrow new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Unmatching clients\", \"Unmatching clients\");\n}\n- if (oldToken.getIssuedAt() < client.getNotBefore()) {\n- throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Stale token\");\n- }\n- if (oldToken.getIssuedAt() < realm.getNotBefore()) {\n- throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Stale token\");\n- }\n- if (oldToken.getIssuedAt() < session.users().getNotBeforeOfUser(realm, user)) {\n+ try {\n+ TokenVerifier.createWithoutSignature(oldToken)\n+ .withChecks(NotBeforeCheck.forModel(client), NotBeforeCheck.forModel(session, realm, user))\n+ .verify();\n+ } catch (VerificationException e) {\nthrow new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Stale token\");\n}\n-\n// Setup clientScopes from refresh token to the context\nString oldTokenScope = oldToken.getScope();\n@@ -207,16 +207,16 @@ public class TokenManager {\n* @throws OAuthErrorException\n*/\npublic boolean checkTokenValidForIntrospection(KeycloakSession session, RealmModel realm, AccessToken token) throws OAuthErrorException {\n- if (!token.isActive()) {\n- return false;\n- }\n-\n- if (token.getIssuedAt() < realm.getNotBefore()) {\n+ ClientModel client = realm.getClientByClientId(token.getIssuedFor());\n+ if (client == null || !client.isEnabled()) {\nreturn false;\n}\n- ClientModel client = realm.getClientByClientId(token.getIssuedFor());\n- if (client == null || !client.isEnabled() || token.getIssuedAt() < client.getNotBefore()) {\n+ try {\n+ TokenVerifier.createWithoutSignature(token)\n+ .withChecks(NotBeforeCheck.forModel(client), TokenVerifier.IS_ACTIVE)\n+ .verify();\n+ } catch (VerificationException e) {\nreturn false;\n}\n@@ -248,9 +248,14 @@ public class TokenManager {\nif (!user.isEnabled()) {\nreturn false;\n}\n- if (token.getIssuedAt() < session.users().getNotBeforeOfUser(realm, user)) {\n+ try {\n+ TokenVerifier.createWithoutSignature(token)\n+ .withChecks(NotBeforeCheck.forModel(session ,realm, user))\n+ .verify();\n+ } catch (VerificationException e) {\nreturn false;\n}\n+\nif (token.getIssuedAt() + 1 < userSession.getStarted()) {\nreturn false;\n}\n@@ -349,12 +354,12 @@ public class TokenManager {\n}\nif (checkExpiration) {\n- if (refreshToken.getExpiration() != 0 && refreshToken.isExpired()) {\n- throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Refresh token expired\");\n- }\n-\n- if (refreshToken.getIssuedAt() < realm.getNotBefore()) {\n- throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Stale refresh token\");\n+ try {\n+ TokenVerifier.createWithoutSignature(refreshToken)\n+ .withChecks(NotBeforeCheck.forModel(realm), TokenVerifier.IS_ACTIVE)\n+ .verify();\n+ } catch (VerificationException e) {\n+ throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, e.getMessage());\n}\n}\n@@ -385,14 +390,12 @@ public class TokenManager {\npublic IDToken verifyIDToken(KeycloakSession session, RealmModel realm, String encodedIDToken) throws OAuthErrorException {\nIDToken idToken = session.tokens().decode(encodedIDToken, IDToken.class);\n- if (idToken == null) {\n- throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Invalid IDToken\");\n- }\n- if (idToken.isExpired()) {\n- throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"IDToken expired\");\n- }\n- if (idToken.getIssuedAt() < realm.getNotBefore()) {\n- throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, \"Stale IDToken\");\n+ try {\n+ TokenVerifier.createWithoutSignature(idToken)\n+ .withChecks(NotBeforeCheck.forModel(realm), TokenVerifier.IS_ACTIVE)\n+ .verify();\n+ } catch (VerificationException e) {\n+ throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, e.getMessage());\n}\nreturn idToken;\n}\n@@ -881,4 +884,44 @@ public class TokenManager {\n}\n}\n+ public static class NotBeforeCheck implements TokenVerifier.Predicate<JsonWebToken> {\n+\n+ private final int notBefore;\n+\n+ public NotBeforeCheck(int notBefore) {\n+ this.notBefore = notBefore;\n+ }\n+\n+ @Override\n+ public boolean test(JsonWebToken t) throws VerificationException {\n+ if (t.getIssuedAt() < notBefore) {\n+ throw new VerificationException(\"Stale token\");\n+ }\n+\n+ return true;\n+ }\n+\n+ public static NotBeforeCheck forModel(ClientModel clientModel) {\n+ if (clientModel != null) {\n+\n+ int notBeforeClient = clientModel.getNotBefore();\n+ int notBeforeRealm = clientModel.getRealm().getNotBefore();\n+\n+ int notBefore = (notBeforeClient == 0 ? notBeforeRealm : (notBeforeRealm == 0 ? notBeforeClient :\n+ Math.min(notBeforeClient, notBeforeRealm)));\n+\n+ return new NotBeforeCheck(notBefore);\n+ }\n+\n+ return new NotBeforeCheck(0);\n+ }\n+\n+ public static NotBeforeCheck forModel(RealmModel realmModel) {\n+ return new NotBeforeCheck(realmModel == null ? 0 : realmModel.getNotBefore());\n+ }\n+\n+ public static NotBeforeCheck forModel(KeycloakSession session, RealmModel realmModel, UserModel userModel) {\n+ return new NotBeforeCheck(session.users().getNotBeforeOfUser(realmModel, userModel));\n+ }\n+ }\n}\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": "@@ -35,6 +35,7 @@ import org.keycloak.jose.jws.JWSBuilder;\nimport org.keycloak.models.AuthenticatedClientSessionModel;\nimport org.keycloak.models.ClientModel;\nimport org.keycloak.models.ClientSessionContext;\n+import org.keycloak.protocol.oidc.TokenManager.NotBeforeCheck;\nimport org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\n@@ -137,6 +138,7 @@ public class UserInfoEndpoint {\n}\nAccessToken token;\n+ ClientModel clientModel;\ntry {\nTokenVerifier<AccessToken> verifier = TokenVerifier.create(tokenString, AccessToken.class).withDefaultChecks()\n.realmUrl(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));\n@@ -145,17 +147,21 @@ public class UserInfoEndpoint {\nverifier.verifierContext(verifierContext);\ntoken = verifier.verify().getToken();\n- } catch (VerificationException e) {\n- event.error(Errors.INVALID_TOKEN);\n- throw newUnauthorizedErrorResponseException(OAuthErrorException.INVALID_TOKEN, \"Token verification failed\");\n- }\n- ClientModel clientModel = realm.getClientByClientId(token.getIssuedFor());\n+ clientModel = realm.getClientByClientId(token.getIssuedFor());\nif (clientModel == null) {\nevent.error(Errors.CLIENT_NOT_FOUND);\nthrow new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, \"Client not found\", Response.Status.BAD_REQUEST);\n}\n+ TokenVerifier.createWithoutSignature(token)\n+ .withChecks(NotBeforeCheck.forModel(clientModel))\n+ .verify();\n+ } catch (VerificationException e) {\n+ event.error(Errors.INVALID_TOKEN);\n+ throw newUnauthorizedErrorResponseException(OAuthErrorException.INVALID_TOKEN, \"Token verification failed\");\n+ }\n+\nif (!clientModel.getProtocol().equals(OIDCLoginProtocol.LOGIN_PROTOCOL)) {\nevent.error(Errors.INVALID_CLIENT);\nthrow new ErrorResponseException(Errors.INVALID_CLIENT, \"Wrong client protocol.\", Response.Status.BAD_REQUEST);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/UserInfoTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/UserInfoTest.java", "diff": "@@ -401,6 +401,65 @@ public class UserInfoTest extends AbstractKeycloakTest {\n}\n}\n+ @Test\n+ public void testNotBeforeTokens() {\n+ Client client = ClientBuilder.newClient();\n+\n+ try {\n+ AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);\n+\n+ int time = Time.currentTime() + 60;\n+\n+ RealmResource realm = adminClient.realm(\"test\");\n+ RealmRepresentation rep = realm.toRepresentation();\n+ rep.setNotBefore(time);\n+ realm.update(rep);\n+\n+ Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());\n+\n+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());\n+\n+ response.close();\n+\n+ events.expect(EventType.USER_INFO_REQUEST_ERROR)\n+ .error(Errors.INVALID_TOKEN)\n+ .user(Matchers.nullValue(String.class))\n+ .session(Matchers.nullValue(String.class))\n+ .detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN)\n+ .client((String) null)\n+ .assertEvent();\n+\n+ events.clear();\n+ rep.setNotBefore(0);\n+ realm.update(rep);\n+\n+ // do the same with client's notBefore\n+ ClientResource clientResource = realm.clients().get(realm.clients().findByClientId(\"test-app\").get(0).getId());\n+ ClientRepresentation clientRep = clientResource.toRepresentation();\n+ clientRep.setNotBefore(time);\n+ clientResource.update(clientRep);\n+\n+ response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());\n+\n+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());\n+\n+ response.close();\n+\n+ events.expect(EventType.USER_INFO_REQUEST_ERROR)\n+ .error(Errors.INVALID_TOKEN)\n+ .user(Matchers.nullValue(String.class))\n+ .session(Matchers.nullValue(String.class))\n+ .detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN)\n+ .client((String) null)\n+ .assertEvent();\n+\n+ clientRep.setNotBefore(0);\n+ clientResource.update(clientRep);\n+ } finally {\n+ client.close();\n+ }\n+ }\n+\n@Test\npublic void testSessionExpiredOfflineAccess() throws Exception {\nClient client = ClientBuilder.newClient();\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-9563 Improve access token checks for userinfo endpoint
339,235
10.02.2020 13:48:08
-3,600
dda829710e9ee8d6d5b01effe5adcc391a0f366b
Require PKCE for admin and account console
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo9_0_0.java", "new_path": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo9_0_0.java", "diff": "@@ -57,6 +57,7 @@ public class MigrateTo9_0_0 implements Migration {\nprotected void migrateRealmCommon(RealmModel realm) {\naddAccountConsoleClient(realm);\naddAccountApiRoles(realm);\n+ enablePkceAdminAccountClients(realm);\n}\nprivate void addAccountApiRoles(RealmModel realm) {\n@@ -100,4 +101,17 @@ public class MigrateTo9_0_0 implements Migration {\nclient.addProtocolMapper(audienceMapper);\n}\n}\n+\n+ private void enablePkceAdminAccountClients(RealmModel realm) {\n+ ClientModel adminConsole = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);\n+ if (adminConsole != null) {\n+ adminConsole.setAttribute(\"pkce.code.challenge.method\", \"S256\");\n+ }\n+\n+ ClientModel accountConsole = realm.getClientByClientId(Constants.ACCOUNT_CONSOLE_CLIENT_ID);\n+ if (accountConsole != null) {\n+ accountConsole.setAttribute(\"pkce.code.challenge.method\", \"S256\");\n+ }\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/managers/RealmManager.java", "new_path": "services/src/main/java/org/keycloak/services/managers/RealmManager.java", "diff": "@@ -41,6 +41,7 @@ import org.keycloak.models.utils.DefaultRequiredActions;\nimport org.keycloak.models.utils.KeycloakModelUtils;\nimport org.keycloak.models.utils.RepresentationToModel;\nimport org.keycloak.protocol.ProtocolMapperUtils;\n+import org.keycloak.protocol.oidc.OIDCConfigAttributes;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocol;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;\nimport org.keycloak.protocol.oidc.mappers.AudienceResolveProtocolMapper;\n@@ -170,6 +171,8 @@ public class RealmManager {\nadminConsole.setPublicClient(true);\nadminConsole.setFullScopeAllowed(false);\nadminConsole.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);\n+\n+ adminConsole.setAttribute(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD, \"S256\");\n}\nprotected void setupAdminConsoleLocaleMapper(RealmModel realm) {\n@@ -461,6 +464,8 @@ public class RealmManager {\naudienceMapper.setProtocolMapper(AudienceResolveProtocolMapper.PROVIDER_ID);\naccountConsoleClient.addProtocolMapper(audienceMapper);\n+\n+ accountConsoleClient.setAttribute(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD, \"S256\");\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java", "diff": "@@ -801,9 +801,8 @@ public class LoginTest extends AbstractTestRealmKeycloakTest {\n@Test\npublic void openLoginFormWithDifferentApplication() throws Exception {\n- // Login form shown after redirect from admin console\n- oauth.clientId(Constants.ADMIN_CONSOLE_CLIENT_ID);\n- oauth.redirectUri(AuthServerTestEnricher.getAuthServerContextRoot() + \"/auth/admin/test/console\");\n+ oauth.clientId(\"root-url-client\");\n+ oauth.redirectUri(\"http://localhost:8180/foo/bar/\");\noauth.openLoginForm();\n// Login form shown after redirect from app\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java", "diff": "@@ -41,6 +41,7 @@ import org.keycloak.models.LDAPConstants;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.utils.DefaultAuthenticationFlows;\nimport org.keycloak.models.utils.TimeBasedOTP;\n+import org.keycloak.protocol.oidc.OIDCConfigAttributes;\nimport org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;\nimport org.keycloak.representations.AccessToken;\nimport org.keycloak.representations.idm.AuthenticationExecutionExportRepresentation;\n@@ -281,6 +282,8 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {\ntestFirstBrokerLoginFlowMigrated(migrationRealm);\ntestAccountClient(masterRealm);\ntestAccountClient(migrationRealm);\n+ testAdminClientPkce(masterRealm);\n+ testAdminClientPkce(migrationRealm);\n}\nprivate void testAccountClient(RealmResource realm) {\n@@ -312,6 +315,11 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {\nassertEquals(1, adminConsoleClient.getWebOrigins().size());\n}\n+ private void testAdminClientPkce(RealmResource realm) {\n+ ClientRepresentation adminConsoleClient = realm.clients().findByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID).get(0);\n+ assertEquals(\"S256\", adminConsoleClient.getAttributes().get(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD));\n+ }\n+\nprivate void testAccountClientUrls(RealmResource realm) {\nClientRepresentation accountConsoleClient = realm.clients().findByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).get(0);\n@@ -331,6 +339,7 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {\nassertFalse(accountConsoleClient.isFullScopeAllowed());\nassertTrue(accountConsoleClient.isStandardFlowEnabled());\nassertFalse(accountConsoleClient.isDirectAccessGrantsEnabled());\n+ assertEquals(\"S256\", accountConsoleClient.getAttributes().get(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD));\nClientResource clientResource = realm.clients().get(accountConsoleClient.getId());\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java", "diff": "@@ -238,8 +238,6 @@ public class AccessTokenTest extends AbstractKeycloakTest {\n// KEYCLOAK-3692\n@Test\npublic void accessTokenWrongCode() throws Exception {\n- oauth.clientId(Constants.ADMIN_CONSOLE_CLIENT_ID);\n- oauth.redirectUri(AuthServerTestEnricher.getAuthServerContextRoot() + \"/auth/admin/test/console/nosuch.html\");\noauth.openLoginForm();\nString actionURI = ActionURIUtils.getActionURIFromPageSource(driver.getPageSource());\n@@ -247,9 +245,9 @@ public class AccessTokenTest extends AbstractKeycloakTest {\noauth.fillLoginForm(\"test-user@localhost\", \"password\");\n- events.expectLogin().client(Constants.ADMIN_CONSOLE_CLIENT_ID).detail(Details.REDIRECT_URI, AuthServerTestEnricher.getAuthServerContextRoot() + \"/auth/admin/test/console/nosuch.html\").assertEvent();\n+ events.expectLogin().assertEvent();\n- OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(loginPageCode, null);\n+ OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(loginPageCode, \"password\");\nassertEquals(400, response.getStatusCode());\nassertNull(response.getRefreshToken());\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LoginStatusIframeEndpointTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LoginStatusIframeEndpointTest.java", "diff": "@@ -38,6 +38,7 @@ import org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.ActionURIUtils;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.oidc.PkceGenerator;\nimport org.keycloak.testsuite.runonserver.ServerVersion;\nimport java.io.IOException;\n@@ -65,9 +66,11 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {\ntry (CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) {\nString redirectUri = URLEncoder.encode(suiteContext.getAuthServerInfo().getContextRoot() + \"/auth/admin/master/console\", \"UTF-8\");\n+ PkceGenerator pkce = new PkceGenerator();\n+\nHttpGet get = new HttpGet(\nsuiteContext.getAuthServerInfo().getContextRoot() + \"/auth/realms/master/protocol/openid-connect/auth?response_type=code&client_id=\" + Constants.ADMIN_CONSOLE_CLIENT_ID +\n- \"&redirect_uri=\" + redirectUri);\n+ \"&redirect_uri=\" + redirectUri + \"&scope=openid&code_challenge_method=S256&code_challenge=\" + pkce.getCodeChallenge());\nCloseableHttpResponse response = client.execute(get);\nString s = IOUtils.toString(response.getEntity().getContent(), \"UTF-8\");\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/PkceGenerator.java", "diff": "+package org.keycloak.testsuite.oidc;\n+\n+import org.keycloak.common.util.Base64Url;\n+\n+import java.security.MessageDigest;\n+import java.util.UUID;\n+\n+public class PkceGenerator {\n+\n+ private String codeVerifier;\n+\n+ private String codeChallenge;\n+\n+ public PkceGenerator() {\n+ codeVerifier = UUID.randomUUID().toString() + \"-\" + UUID.randomUUID().toString(); // Good enough for testing, but shouldn't be used elsewhere\n+ codeChallenge = generateS256CodeChallenge(codeVerifier);\n+ }\n+\n+ public PkceGenerator(String codeVerifier) {\n+ this.codeVerifier = codeVerifier;\n+ codeChallenge = generateS256CodeChallenge(codeVerifier);\n+ }\n+\n+ public String getCodeVerifier() {\n+ return codeVerifier;\n+ }\n+\n+ public String getCodeChallenge() {\n+ return codeChallenge;\n+ }\n+\n+ private String generateS256CodeChallenge(String codeVerifier) {\n+ try {\n+ MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n+ md.update(codeVerifier.getBytes(\"ISO_8859_1\"));\n+ byte[] digestBytes = md.digest();\n+ String codeChallenge = Base64Url.encode(digestBytes);\n+ return codeChallenge;\n+ } catch (Exception e) {\n+ throw new RuntimeException(e);\n+ }\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12829 Require PKCE for admin and account console
339,235
07.02.2020 09:34:36
-3,600
0b8adc78740046c14c6736a950a18cf992f90f18
Fix NPE in client validation on startup
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/util/ResolveRelative.java", "new_path": "services/src/main/java/org/keycloak/services/util/ResolveRelative.java", "diff": "@@ -22,32 +22,43 @@ import org.keycloak.models.KeycloakSession;\nimport org.keycloak.urls.UrlType;\nimport javax.ws.rs.core.UriBuilder;\n-import java.net.URI;\n/**\n* @author <a href=\"mailto:[email protected]\">Bill Burke</a>\n* @version $Revision: 1 $\n*/\npublic class ResolveRelative {\n+\npublic static String resolveRelativeUri(KeycloakSession session, String rootUrl, String url) {\n+ String frontendUrl = session.getContext().getUri(UrlType.FRONTEND).getBaseUri().toString();\n+ String adminUrl = session.getContext().getUri(UrlType.ADMIN).getBaseUri().toString();\n+ return resolveRelativeUri(frontendUrl, adminUrl, rootUrl, url);\n+ }\n+\n+ public static String resolveRelativeUri(String frontendUrl, String adminUrl, String rootUrl, String url) {\nif (url == null || !url.startsWith(\"/\")) {\nreturn url;\n} else if (rootUrl != null) {\n- return resolveRootUrl(session, rootUrl) + url;\n+ return resolveRootUrl(frontendUrl, adminUrl, rootUrl) + url;\n} else {\n- return session.getContext().getUri().getBaseUriBuilder().replacePath(url).build().toString();\n+ return UriBuilder.fromUri(frontendUrl).replacePath(url).build().toString();\n}\n}\n-\npublic static String resolveRootUrl(KeycloakSession session, String rootUrl) {\n+ String frontendUrl = session.getContext().getUri(UrlType.FRONTEND).getBaseUri().toString();\n+ String adminUrl = session.getContext().getUri(UrlType.ADMIN).getBaseUri().toString();\n+ return resolveRootUrl(frontendUrl, adminUrl, rootUrl);\n+ }\n+\n+ public static String resolveRootUrl(String frontendUrl, String adminUrl, String rootUrl) {\nif (rootUrl != null) {\nif (rootUrl.equals(Constants.AUTH_BASE_URL_PROP)) {\n- rootUrl = session.getContext().getUri(UrlType.FRONTEND).getBaseUri().toString();\n+ rootUrl = frontendUrl;\nif (rootUrl.endsWith(\"/\")) {\nrootUrl = rootUrl.substring(0, rootUrl.length() - 1);\n}\n} else if (rootUrl.equals(Constants.AUTH_ADMIN_URL_PROP)) {\n- rootUrl = session.getContext().getUri(UrlType.ADMIN).getBaseUri().toString();\n+ rootUrl = adminUrl;\nif (rootUrl.endsWith(\"/\")) {\nrootUrl = rootUrl.substring(0, rootUrl.length() - 1);\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": "@@ -41,8 +41,11 @@ public class DefaultClientValidationProvider implements ClientValidationProvider\n}\nprivate void validate(ClientModel client) throws ValidationException {\n- String resolvedRootUrl = ResolveRelative.resolveRootUrl(context.getSession(), client.getRootUrl());\n- String resolvedBaseUrl = ResolveRelative.resolveRelativeUri(context.getSession(), resolvedRootUrl, client.getBaseUrl());\n+ // Use a fake URL for validating relative URLs as we may not be validating clients in the context of a request (import at startup)\n+ String authServerUrl = \"https://localhost/auth\";\n+\n+ String resolvedRootUrl = ResolveRelative.resolveRootUrl(authServerUrl, authServerUrl, client.getRootUrl());\n+ String resolvedBaseUrl = ResolveRelative.resolveRelativeUri(authServerUrl, authServerUrl, resolvedRootUrl, client.getBaseUrl());\nvalidateRootUrl(resolvedRootUrl);\nvalidateBaseUrl(resolvedBaseUrl);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ImportTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ImportTest.java", "diff": "package org.keycloak.testsuite.model;\n+import org.apache.commons.io.IOUtils;\nimport org.junit.Assert;\nimport org.junit.FixMethodOrder;\nimport org.junit.Test;\nimport org.junit.runners.MethodSorters;\n-import org.keycloak.common.constants.KerberosConstants;\n+import org.keycloak.authorization.policy.evaluation.Realm;\nimport org.keycloak.models.Constants;\n-import org.keycloak.models.ProtocolMapperModel;\n+import org.keycloak.models.KeycloakSession;\nimport org.keycloak.models.RealmModel;\n-import org.keycloak.models.RequiredCredentialModel;\n-import org.keycloak.protocol.oidc.OIDCLoginProtocol;\n-import org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper;\n-import org.keycloak.protocol.oidc.mappers.UserSessionNoteMapper;\nimport org.keycloak.representations.idm.RealmRepresentation;\n+import org.keycloak.services.managers.RealmManager;\nimport org.keycloak.testsuite.AbstractTestRealmKeycloakTest;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\n+import org.keycloak.testsuite.runonserver.RunOnServerException;\n+import org.keycloak.util.JsonSerialization;\n-import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;\n+import java.io.IOException;\n+import java.nio.charset.StandardCharsets;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+import java.util.concurrent.atomic.AtomicReference;\n-import java.util.List;\n-import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\n+import static org.junit.Assert.assertTrue;\n+import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;\n/**\n@@ -48,13 +52,13 @@ import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.A\npublic class ImportTest extends AbstractTestRealmKeycloakTest {\n@Test\n- public void demoDelete() throws Exception {\n+ public void demoDelete() {\n// was having trouble deleting this realm from admin console\nremoveRealm(\"demo-delete\");\n}\n@Test\n- public void install2() throws Exception {\n+ public void install2() {\ntestingClient.server().run(session -> {\nRealmModel realm = session.realms().getRealmByName(\"demo\");\n@@ -66,22 +70,50 @@ public class ImportTest extends AbstractTestRealmKeycloakTest {\n});\n}\n- private static void verifyRequiredCredentials(List<RequiredCredentialModel> requiredCreds, String expectedType) {\n+ // KEYCLOAK-12921 NPE importing realm with no request context\n+ @Test\n+ public void importWithoutRequestContext() throws IOException {\n+ final String realmString = IOUtils.toString(getClass().getResourceAsStream(\"/model/realm-validation.json\"), StandardCharsets.UTF_8);\n+\n+ testingClient.server().run(session -> {\n+ RealmRepresentation testRealm = JsonSerialization.readValue(realmString, RealmRepresentation.class);\n- Assert.assertEquals(1, requiredCreds.size());\n- Assert.assertEquals(expectedType, requiredCreds.get(0).getType());\n- }\n+ AtomicReference<Throwable> err = new AtomicReference<>();\n+\n+ // Need a new thread to not get context from thread processing request to run-on-server endpoint\n+ Thread t = new Thread(() -> {\n+ try {\n+ KeycloakSession session2 = session.getKeycloakSessionFactory().create();\n+ session2.getContext().setRealm(session.getContext().getRealm());\n+ session2.getTransactionManager().begin();\n+\n+ RealmModel realmModel = new RealmManager(session2).importRealm(testRealm);\n- private static void assertGssProtocolMapper(ProtocolMapperModel gssCredentialMapper) {\n+ session2.getTransactionManager().commit();\n- Assert.assertEquals(KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME, gssCredentialMapper.getName());\n- Assert.assertEquals( OIDCLoginProtocol.LOGIN_PROTOCOL, gssCredentialMapper.getProtocol());\n- Assert.assertEquals(UserSessionNoteMapper.PROVIDER_ID, gssCredentialMapper.getProtocolMapper());\n- String includeInAccessToken = gssCredentialMapper.getConfig().get(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN);\n- String includeInIdToken = gssCredentialMapper.getConfig().get(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN);\n- Assert.assertTrue(includeInAccessToken.equalsIgnoreCase(\"true\"));\n- Assert.assertTrue(includeInIdToken == null || Boolean.parseBoolean(includeInIdToken) == false);\n+ session2.getTransactionManager().begin();\n+ session.realms().removeRealm(realmModel.getId());\n+ session2.getTransactionManager().commit();\n+ session2.close();\n+ } catch (Throwable th) {\n+ err.set(th);\n+ }\n+ });\n+\n+ synchronized (t) {\n+ t.start();\n+ try {\n+ t.wait(10000);\n+ } catch (InterruptedException e) {\n+ throw new RunOnServerException(e);\n+ }\n+ }\n+\n+ if (err.get() != null) {\n+ throw new RunOnServerException(err.get());\n+ }\n+ });\n}\n@Override\n@@ -97,4 +129,5 @@ public class ImportTest extends AbstractTestRealmKeycloakTest {\ntestRealm.setId(\"demo\");\nadminClient.realms().create(testRealm);\n}\n+\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/tests/base/src/test/resources/model/realm-validation.json", "diff": "+{\n+ \"realm\": \"realm-validation\",\n+ \"clients\": [\n+ {\n+ \"name\": \"my-client\",\n+ \"baseUrl\": \"/product-portal\"\n+ }\n+ ]\n+}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12921 Fix NPE in client validation on startup
339,235
06.02.2020 07:17:52
-3,600
3c0cf8463aea85f4658ff764f53f24853dcd7296
Check if action is disabled in realm before executing
[ { "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": "@@ -1118,6 +1118,10 @@ public class AuthenticationManager {\nlogger.debugv(\"Requested action {0} does not support being invoked with kc_action\", factory.getId());\nsetKcActionStatus(factory.getId(), RequiredActionContext.KcActionStatus.ERROR, authSession);\nreturn null;\n+ } else if (!model.isEnabled()) {\n+ logger.debugv(\"Requested action {0} is disabled and can't be invoked with kc_action\", factory.getId());\n+ setKcActionStatus(factory.getId(), RequiredActionContext.KcActionStatus.ERROR, authSession);\n+ return null;\n} else {\nauthSession.setClientNote(Constants.KC_ACTION_EXECUTING, factory.getId());\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTest.java", "diff": "+/*\n+ * Copyright 2018 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.actions;\n+\n+import org.jboss.arquillian.graphene.page.Page;\n+import org.junit.Rule;\n+import org.junit.Test;\n+import org.keycloak.authentication.requiredactions.TermsAndConditions;\n+import org.keycloak.models.UserModel;\n+import org.keycloak.representations.idm.RealmRepresentation;\n+import org.keycloak.representations.idm.RequiredActionProviderRepresentation;\n+import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;\n+import org.keycloak.testsuite.AssertEvents;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\n+import org.keycloak.testsuite.pages.AppPage;\n+import org.keycloak.testsuite.pages.LoginPage;\n+\n+import static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertTrue;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Hiroyuki Wada</a>\n+ */\n+@AuthServerContainerExclude(AuthServer.REMOTE)\n+public class AppInitiatedActionTest extends AbstractTestRealmKeycloakTest {\n+\n+ @Override\n+ public void configureTestRealm(RealmRepresentation testRealm) {\n+ }\n+\n+ @Rule\n+ public AssertEvents events = new AssertEvents(this);\n+\n+ @Page\n+ protected AppPage appPage;\n+\n+ @Page\n+ protected LoginPage loginPage;\n+\n+ @Test\n+ public void executeUnknownAction() {\n+ oauth.kcAction(\"nosuch\").openLoginForm();\n+\n+ loginPage.login(\"test-user@localhost\", \"password\");\n+\n+ assertTrue(appPage.isCurrent());\n+\n+ String kcActionStatus = oauth.getCurrentQuery().get(\"kc_action_status\");\n+ assertEquals(\"error\", kcActionStatus);\n+ }\n+\n+ @Test\n+ public void executeUnsupportedAction() {\n+ oauth.kcAction(TermsAndConditions.PROVIDER_ID).openLoginForm();\n+\n+ loginPage.login(\"test-user@localhost\", \"password\");\n+\n+ assertTrue(appPage.isCurrent());\n+\n+ String kcActionStatus = oauth.getCurrentQuery().get(\"kc_action_status\");\n+ assertEquals(\"error\", kcActionStatus);\n+ }\n+\n+ @Test\n+ public void executeDisabledAction() {\n+ RequiredActionProviderRepresentation configureTotp = testRealm().flows().getRequiredAction(\"CONFIGURE_TOTP\");\n+ configureTotp.setEnabled(false);\n+ try {\n+ testRealm().flows().updateRequiredAction(\"CONFIGURE_TOTP\", configureTotp);\n+\n+ oauth.kcAction(UserModel.RequiredAction.CONFIGURE_TOTP.name()).openLoginForm();\n+\n+ loginPage.login(\"test-user@localhost\", \"password\");\n+\n+ assertTrue(appPage.isCurrent());\n+\n+ String kcActionStatus = oauth.getCurrentQuery().get(\"kc_action_status\");\n+ assertEquals(\"error\", kcActionStatus);\n+ } finally {\n+ configureTotp.setEnabled(true);\n+ testRealm().flows().updateRequiredAction(\"CONFIGURE_TOTP\", configureTotp);\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTotpSetupTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTotpSetupTest.java", "diff": "@@ -136,10 +136,7 @@ public class AppInitiatedActionTotpSetupTest extends AbstractAppInitiatedActionT\nloginPage.login(\"test-user@localhost\", \"password\");\n- totpPage.assertCurrent();\n- totpPage.cancel();\n-\n- assertKcActionStatus(\"cancelled\");\n+ assertKcActionStatus(\"error\");\n} finally {\n// Revert the realm setup changes done within the test\npostConfigureRealmForCancelSetupTotpTest();\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12821 Check if action is disabled in realm before executing
339,343
13.12.2019 10:42:11
-3,600
622a97bd1c3044760b2166301864da9941cae131
Sensitive Data Exposure from patch of hiba haddad
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/events/Details.java", "new_path": "server-spi-private/src/main/java/org/keycloak/events/Details.java", "diff": "@@ -50,8 +50,6 @@ public interface Details {\nString SCOPE = \"scope\";\nString REQUESTED_ISSUER = \"requested_issuer\";\nString REQUESTED_SUBJECT = \"requested_subject\";\n- String CLIENT_SESSION_STATE = \"client_session_state\";\n- String CLIENT_SESSION_HOST = \"client_session_host\";\nString RESTART_AFTER_TIMEOUT = \"restart_after_timeout\";\nString CONSENT = \"consent\";\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": "@@ -537,13 +537,11 @@ public class TokenEndpoint {\nString adapterSessionHost = formParams.getFirst(AdapterConstants.CLIENT_SESSION_HOST);\nlogger.debugf(\"Adapter Session '%s' saved in ClientSession for client '%s'. Host is '%s'\", adapterSessionId, client.getClientId(), adapterSessionHost);\n- event.detail(AdapterConstants.CLIENT_SESSION_STATE, adapterSessionId);\nString oldClientSessionState = clientSession.getNote(AdapterConstants.CLIENT_SESSION_STATE);\nif (!adapterSessionId.equals(oldClientSessionState)) {\nclientSession.setNote(AdapterConstants.CLIENT_SESSION_STATE, adapterSessionId);\n}\n- event.detail(AdapterConstants.CLIENT_SESSION_HOST, adapterSessionHost);\nString oldClientSessionHost = clientSession.getNote(AdapterConstants.CLIENT_SESSION_HOST);\nif (!Objects.equals(adapterSessionHost, oldClientSessionHost)) {\nclientSession.setNote(AdapterConstants.CLIENT_SESSION_HOST, adapterSessionHost);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthDanceClientSessionExtensionTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthDanceClientSessionExtensionTest.java", "diff": "@@ -71,8 +71,6 @@ public class OAuthDanceClientSessionExtensionTest extends AbstractKeycloakTest {\nString refreshTokenString = tokenResponse.getRefreshToken();\nEventRepresentation tokenEvent = events.expectCodeToToken(codeId, sessionId)\n- .detail(Details.CLIENT_SESSION_STATE, clientSessionState)\n- .detail(Details.CLIENT_SESSION_HOST, clientSessionHost)\n.assertEvent();\n@@ -83,10 +81,7 @@ public class OAuthDanceClientSessionExtensionTest extends AbstractKeycloakTest {\n.doRefreshTokenRequest(refreshTokenString, \"password\");\nevents.expectRefresh(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId)\n- .detail(Details.CLIENT_SESSION_STATE, updatedClientSessionState)\n- .detail(Details.CLIENT_SESSION_HOST, clientSessionHost)\n.assertEvent();\n}\n-\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12228 Sensitive Data Exposure from patch of hiba haddad [email protected]
339,343
11.02.2020 16:33:04
-3,600
96c2fffd1e5f1a64cef4251f338ed2695926f696
removal of xstream license references as this dependency has been removed
[ { "change_type": "DELETE", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/com.thoughtworks.xstream,xstream,1.4.10,BSD 3-clause New or Revised License.txt", "new_path": null, "diff": "-(BSD Style License)\n-\n-Copyright (c) 2003-2006, Joe Walnes\n-Copyright (c) 2006-2015, XStream Committers\n-All rights reserved.\n-\n-Redistribution and use in source and binary forms, with or without\n-modification, are permitted provided that the following conditions are met:\n-\n-Redistributions of source code must retain the above copyright notice, this list of\n-conditions and the following disclaimer. Redistributions in binary form must reproduce\n-the above copyright notice, this list of conditions and the following disclaimer in\n-the documentation and/or other materials provided with the distribution.\n-\n-Neither the name of XStream nor the names of its contributors may be used to endorse\n-or promote products derived from this software without specific prior written\n-permission.\n-\n-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n-EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n-OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n-SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n-TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n-BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n-CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n-WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n-DAMAGE.\n" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/keycloak/licenses.xml", "diff": "</license>\n</licenses>\n</dependency>\n- <dependency>\n- <groupId>com.thoughtworks.xstream</groupId>\n- <artifactId>xstream</artifactId>\n- <version>1.4.10</version>\n- <licenses>\n- <license>\n- <name>BSD 3-clause New or Revised License</name>\n- <url>https://raw.githubusercontent.com/x-stream/xstream/XSTREAM_1_4_10/LICENSE.txt</url>\n- </license>\n- </licenses>\n- </dependency>\n<dependency>\n<groupId>org.kie</groupId>\n<artifactId>kie-api</artifactId>\n" }, { "change_type": "DELETE", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/com.thoughtworks.xstream,xstream,1.4.10,BSD 3-clause New or Revised License.txt", "new_path": null, "diff": "-(BSD Style License)\n-\n-Copyright (c) 2003-2006, Joe Walnes\n-Copyright (c) 2006-2015, XStream Committers\n-All rights reserved.\n-\n-Redistribution and use in source and binary forms, with or without\n-modification, are permitted provided that the following conditions are met:\n-\n-Redistributions of source code must retain the above copyright notice, this list of\n-conditions and the following disclaimer. Redistributions in binary form must reproduce\n-the above copyright notice, this list of conditions and the following disclaimer in\n-the documentation and/or other materials provided with the distribution.\n-\n-Neither the name of XStream nor the names of its contributors may be used to endorse\n-or promote products derived from this software without specific prior written\n-permission.\n-\n-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n-EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n-OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n-SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n-TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n-BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n-CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n-WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n-DAMAGE.\n" }, { "change_type": "MODIFY", "old_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "new_path": "distribution/feature-packs/server-feature-pack/src/main/resources/licenses/rh-sso/licenses.xml", "diff": "</license>\n</licenses>\n</dependency>\n- <dependency>\n- <groupId>com.thoughtworks.xstream</groupId>\n- <artifactId>xstream</artifactId>\n- <version>1.4.10</version>\n- <licenses>\n- <license>\n- <name>BSD 3-clause New or Revised License</name>\n- <url>https://raw.githubusercontent.com/x-stream/xstream/XSTREAM_1_4_10/LICENSE.txt</url>\n- </license>\n- </licenses>\n- </dependency>\n<dependency>\n<groupId>org.kie</groupId>\n<artifactId>kie-api</artifactId>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-11930 removal of xstream license references as this dependency has been removed
339,281
11.02.2020 15:32:11
-3,600
3d22644bbe0e95638059ff077c83c119b6f00f72
Fix WelcomePageTest on Postgresql
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/helpers/DropAllServlet.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/helpers/DropAllServlet.java", "diff": "@@ -112,14 +112,12 @@ public class DropAllServlet extends HttpServlet {\n\"_drop_table_ COMPONENT_CONFIG _cascade_;\\n\" +\n\"_drop_table_ COMPONENT _cascade_;\\n\" +\n\"_drop_table_ COMPOSITE_ROLE _cascade_;\\n\" +\n- \"_drop_table_ CREDENTIAL_ATTRIBUTE _cascade_;\\n\" +\n\"_drop_table_ CREDENTIAL _cascade_;\\n\" +\n\"_drop_table_ DEFAULT_CLIENT_SCOPE _cascade_;\\n\" +\n\"_drop_table_ EVENT_ENTITY _cascade_;\\n\" +\n\"_drop_table_ EXAMPLE_COMPANY _cascade_;\\n\" +\n\"_drop_table_ FEDERATED_IDENTITY _cascade_;\\n\" +\n\"_drop_table_ FEDERATED_USER _cascade_;\\n\" +\n- \"_drop_table_ FED_CREDENTIAL_ATTRIBUTE _cascade_;\\n\" +\n\"_drop_table_ FED_USER_ATTRIBUTE _cascade_;\\n\" +\n\"_drop_table_ FED_USER_CONSENT _cascade_;\\n\" +\n\"_drop_table_ FED_USER_CONSENT_CL_SCOPE _cascade_;\\n\" +\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12237 Fix WelcomePageTest on Postgresql
339,459
05.02.2020 10:06:17
-3,600
b0ffea699e662f868bddfd076aa8cb8ad841aaa4
Improve the OTP login form created and implemented login form design, where OTP device can be selected implemented selectable-card-view logic in jQuery edited related css and ftl theme resources fixed affected BrowserFlow tests
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/events/Details.java", "new_path": "server-spi-private/src/main/java/org/keycloak/events/Details.java", "diff": "@@ -73,4 +73,5 @@ public interface Details {\nString X509_CERTIFICATE_ISSUER_DISTINGUISHED_NAME = \"x509_cert_issuer_distinguished_name\";\nString CREDENTIAL_TYPE = \"credential_type\";\n+ String SELECTED_CREDENTIAL_ID = \"selected_credential_id\";\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/authenticators/browser/OTPFormAuthenticator.java", "new_path": "services/src/main/java/org/keycloak/authentication/authenticators/browser/OTPFormAuthenticator.java", "diff": "@@ -27,6 +27,7 @@ import org.keycloak.authentication.requiredactions.UpdateTotp;\nimport org.keycloak.credential.CredentialProvider;\nimport org.keycloak.credential.OTPCredentialProvider;\nimport org.keycloak.credential.OTPCredentialProviderFactory;\n+import org.keycloak.events.Details;\nimport org.keycloak.events.Errors;\nimport org.keycloak.forms.login.LoginFormsProvider;\nimport org.keycloak.models.KeycloakSession;\n@@ -79,6 +80,8 @@ public class OTPFormAuthenticator extends AbstractUsernameFormAuthenticator impl\n.getDefaultCredential(context.getSession(), context.getRealm(), context.getUser());\ncredentialId = defaultOtpCredential==null ? \"\" : defaultOtpCredential.getId();\n}\n+ context.getEvent().detail(Details.SELECTED_CREDENTIAL_ID, credentialId);\n+\ncontext.form().setAttribute(SELECTED_OTP_CREDENTIAL_ID, credentialId);\nUserModel userModel = context.getUser();\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java", "diff": "@@ -20,11 +20,13 @@ import java.util.List;\nimport java.util.stream.Collectors;\nimport org.junit.Assert;\n+import org.keycloak.common.util.Retry;\n+import org.keycloak.testsuite.util.UIUtils;\n+import org.keycloak.testsuite.util.WaitUtils;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.NoSuchElementException;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.support.FindBy;\n-import org.openqa.selenium.support.ui.Select;\n/**\n* @author <a href=\"mailto:[email protected]\">Stian Thorgersen</a>\n@@ -43,9 +45,6 @@ public class LoginTotpPage extends LanguageComboboxAwarePage {\n@FindBy(className = \"alert-error\")\nprivate WebElement loginErrorMessage;\n- @FindBy(id = \"selected-credential-id\")\n- private WebElement selectedCredentialCombobox;\n-\npublic void login(String totp) {\notpInput.clear();\nif (totp != null) otpInput.sendKeys(totp);\n@@ -75,7 +74,7 @@ public class LoginTotpPage extends LanguageComboboxAwarePage {\n// If false, we don't expect that credentials combobox is available. If true, we expect that it is available on the page\npublic void assertOtpCredentialSelectorAvailability(boolean expectedAvailability) {\ntry {\n- driver.findElement(By.id(\"selected-credential-id\"));\n+ driver.findElement(By.className(\"card-pf-view-single-select\"));\nAssert.assertTrue(expectedAvailability);\n} catch (NoSuchElementException nse) {\nAssert.assertFalse(expectedAvailability);\n@@ -84,29 +83,50 @@ public class LoginTotpPage extends LanguageComboboxAwarePage {\npublic List<String> getAvailableOtpCredentials() {\n- return new Select(selectedCredentialCombobox).getOptions()\n- .stream()\n- .map(WebElement::getText)\n- .collect(Collectors.toList());\n+ return driver.findElements(getXPathForLookupAllCards())\n+ .stream().map(WebElement::getText).collect(Collectors.toList());\n}\npublic String getSelectedOtpCredential() {\n- return new Select(selectedCredentialCombobox).getOptions()\n- .stream()\n- .filter(webElement -> webElement.getAttribute(\"selected\") != null)\n- .findFirst()\n- .orElseThrow(() -> {\n+ try {\n+ WebElement selected = driver.findElement(getXPathForLookupActiveCard());\n+ return selected.getText();\n+ } catch (NoSuchElementException nse) {\n+ // No selected element found\n+ return null;\n+ }\n+ }\n+\n+ private By getXPathForLookupAllCards() {\n+ return By.xpath(\"//div[contains(@class, 'card-pf-view-single-select')]//h2\");\n+ }\n- return new AssertionError(\"Selected OTP credential not found\");\n+ private By getXPathForLookupActiveCard() {\n+ return By.xpath(\"//div[contains(@class, 'card-pf-view-single-select active')]//h2\");\n+ }\n- })\n- .getText();\n+ private By getXPathForLookupCardWithName(String credentialName) {\n+ return By.xpath(\"//div[contains(@class, 'card-pf-view-single-select')]//h2[normalize-space() = '\"+ credentialName +\"']\");\n}\npublic void selectOtpCredential(String credentialName) {\n- new Select(selectedCredentialCombobox).selectByVisibleText(credentialName);\n+ waitForElement(getXPathForLookupActiveCard());\n+\n+ WebElement webElement = driver.findElement(\n+ getXPathForLookupCardWithName(credentialName));\n+ UIUtils.clickLink(webElement);\n+ }\n+\n+\n+ // Workaround, but works with HtmlUnit (WaitUtils.waitForElement doesn't). Find better solution for the future...\n+ private void waitForElement(By by) {\n+ Retry.executeWithBackoff((currentCount) -> {\n+\n+ driver.findElement(by);\n+\n+ }, 10, 10);\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/login/login-otp.ftl", "new_path": "themes/src/main/resources/theme/base/login/login-otp.ftl", "diff": "<#if section=\"header\">\n${msg(\"doLogIn\")}\n<#elseif section=\"form\">\n- <form id=\"kc-otp-login-form\" class=\"${properties.kcFormClass!}\" action=\"${url.loginAction}\" method=\"post\">\n-\n+ <form id=\"kc-otp-login-form\" class=\"${properties.kcFormClass!}\" action=\"${url.loginAction}\"\n+ method=\"post\">\n<#if otpLogin.userOtpCredentials?size gt 1>\n<div class=\"${properties.kcFormGroupClass!}\">\n- <div class=\"${properties.kcLabelWrapperClass!}\">\n- <label for=\"selected-credential-id\" class=\"${properties.kcLabelClass!}\">${msg(\"loginCredential\")}</label>\n- </div>\n<div class=\"${properties.kcInputWrapperClass!}\">\n- <select id=\"selected-credential-id\" name=\"selectedCredentialId\" class=\"form-control\" size=\"1\">\n<#list otpLogin.userOtpCredentials as otpCredential>\n- <option value=\"${otpCredential.id}\" <#if otpCredential.id == otpLogin.selectedCredentialId>selected</#if>>${otpCredential.userLabel}</option>\n+ <div class=\"${properties.kcSelectOTPListClass!}\">\n+ <input type=\"hidden\" value=\"${otpCredential.id}\">\n+ <div class=\"${properties.kcSelectOTPListItemClass!}\">\n+ <span class=\"${properties.kcAuthenticatorOtpCircleClass!}\"></span>\n+ <h2 class=\"${properties.kcSelectOTPItemHeadingClass!}\">\n+ ${otpCredential.userLabel}\n+ </h2>\n+ </div>\n+ </div>\n</#list>\n- </select>\n</div>\n</div>\n</#if>\n</div>\n<div id=\"kc-form-buttons\" class=\"${properties.kcFormButtonsClass!}\">\n- <input class=\"${properties.kcButtonClass!} ${properties.kcButtonPrimaryClass!} ${properties.kcButtonBlockClass!} ${properties.kcButtonLargeClass!}\"\n+ <input\n+ class=\"${properties.kcButtonClass!} ${properties.kcButtonPrimaryClass!} ${properties.kcButtonBlockClass!} ${properties.kcButtonLargeClass!}\"\nname=\"login\" id=\"kc-login\" type=\"submit\" value=\"${msg(\"doLogIn\")}\" />\n</div>\n</div>\n</form>\n+ <script type=\"text/javascript\" src=\"${url.resourcesPath}/node_modules/jquery/dist/jquery.min.js\"></script>\n+ <script type=\"text/javascript\">\n+ $(document).ready(function() {\n+ // Card Single Select\n+ $('.card-pf-view-single-select').click(function() {\n+ if ($(this).hasClass('active'))\n+ { $(this).removeClass('active'); $(this).children().removeAttr('name'); }\n+ else\n+ { $('.card-pf-view-single-select').removeClass('active');\n+ $('.card-pf-view-single-select').children().removeAttr('name');\n+ $(this).addClass('active'); $(this).children().attr('name', 'selectedCredentialId'); }\n+ });\n+\n+ var defaultCred = $('.card-pf-view-single-select')[0];\n+ if (defaultCred) {\n+ defaultCred.click();\n+ }\n+ });\n+ </script>\n</#if>\n</@layout.registrationLayout>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak/login/resources/css/login.css", "new_path": "themes/src/main/resources/theme/keycloak/login/resources/css/login.css", "diff": "@@ -511,6 +511,10 @@ a.zocial {\nwidth: 100%;\n}\n+.login-pf-page .card-pf{\n+ margin-bottom: 10px;\n+}\n+\n#kc-form-login div.form-group:last-of-type,\n#kc-register-form div.form-group:last-of-type,\n#kc-update-profile-form div.form-group:last-of-type {\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak/login/theme.properties", "new_path": "themes/src/main/resources/theme/keycloak/login/theme.properties", "diff": "@@ -86,3 +86,9 @@ kcAuthenticatorPasswordClass=fa fa-unlock list-view-pf-icon-lg\nkcAuthenticatorOTPClass=fa fa-mobile list-view-pf-icon-lg\nkcAuthenticatorWebAuthnClass=fa fa-key list-view-pf-icon-lg\nkcAuthenticatorWebAuthnPasswordlessClass=fa fa-key list-view-pf-icon-lg\n+\n+##### css classes for the OTP Login Form\n+kcSelectOTPListClass=card-pf card-pf-view card-pf-view-select card-pf-view-single-select\n+kcSelectOTPListItemClass=card-pf-body card-pf-top-element\n+kcAuthenticatorOtpCircleClass=fa fa-mobile card-pf-icon-circle\n+kcSelectOTPItemHeadingClass=card-pf-title text-center\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12186 Improve the OTP login form -created and implemented login form design, where OTP device can be selected -implemented selectable-card-view logic in jQuery -edited related css and ftl theme resources -fixed affected BrowserFlow tests Signed-off-by: Peter Zaoral <[email protected]>
339,179
12.02.2020 09:33:31
-3,600
f28ca30e6df92f85fb9037729c710d5728dffed5
Exclude testNoPortInDestination test for remote container
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BasicSamlTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BasicSamlTest.java", "diff": "@@ -13,6 +13,8 @@ import org.keycloak.saml.processing.api.saml.v2.request.SAML2Request;\nimport org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder;\nimport org.keycloak.saml.processing.web.util.RedirectBindingUtil;\nimport org.keycloak.services.resources.RealmsResource;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\nimport org.keycloak.testsuite.util.KeyUtils;\nimport org.keycloak.testsuite.util.Matchers;\nimport org.keycloak.testsuite.util.SamlClient;\n@@ -158,6 +160,7 @@ public class BasicSamlTest extends AbstractSamlTest {\n}\n@Test\n+ @AuthServerContainerExclude(AuthServer.REMOTE)\npublic void testNoPortInDestination() throws Exception {\n// note that this test relies on settings of the login-protocol.saml.knownProtocols configuration option\ntestWithOverriddenPort(-1, Response.Status.OK, containsString(\"login\"));\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12963 Exclude testNoPortInDestination test for remote container
339,179
12.02.2020 09:32:03
-3,600
1bb238d20f76905a41f8a3ed23d0eaad3c5f4212
Use maven-plugin to configure shrinkwrap resolver
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AuthServerTestEnricher.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AuthServerTestEnricher.java", "diff": "@@ -349,8 +349,7 @@ public class AuthServerTestEnricher {\npublic void deployProviders(@Observes(precedence = -1) AfterStart event) throws DeploymentException {\nif (isAuthServerRemote() && currentContainerName.contains(\"auth-server\")) {\nthis.testsuiteProvidersArchive = ShrinkWrap.create(ZipImporter.class, \"testsuiteProviders.jar\")\n- .importFrom(Maven.resolver()\n- .loadPomFromFile(\"pom.xml\")\n+ .importFrom(Maven.configureResolverViaPlugin()\n.resolve(\"org.keycloak.testsuite:integration-arquillian-testsuite-providers\")\n.withoutTransitivity()\n.asSingleFile()\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/adapters/jboss/remote/pom.xml", "new_path": "testsuite/integration-arquillian/tests/other/adapters/jboss/remote/pom.xml", "diff": "<artifactId>commons-csv</artifactId>\n<version>1.2</version>\n</dependency>\n+ <dependency>\n+ <groupId>org.keycloak.testsuite</groupId>\n+ <artifactId>integration-arquillian-testsuite-providers</artifactId>\n+ <version>${project.version}</version>\n+ </dependency>\n</dependencies>\n<build>\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12950 Use maven-plugin to configure shrinkwrap resolver
339,179
12.02.2020 12:38:36
-3,600
c3f0b342bfbeece5b19d9cca33831a3af2947922
Fix adapter remote tests execution deciding
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AppServerTestEnricher.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AppServerTestEnricher.java", "diff": "@@ -316,6 +316,10 @@ public class AppServerTestEnricher {\nreturn CURRENT_APP_SERVER.contains(\"fuse\");\n}\n+ public static boolean isRemoteAppServer() {\n+ return CURRENT_APP_SERVER.contains(\"remote\");\n+ }\n+\nprivate boolean isJBossBased() {\nreturn testContext.getAppServerInfo().isJBossBased();\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/decider/AuthServerExcludeExecutionDecider.java", "new_path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/decider/AuthServerExcludeExecutionDecider.java", "diff": "@@ -23,6 +23,7 @@ import org.jboss.arquillian.test.spi.execution.ExecutionDecision;\nimport org.jboss.arquillian.test.spi.execution.TestExecutionDecider;\nimport org.jboss.arquillian.core.api.Instance;\nimport org.jboss.arquillian.core.api.annotation.Inject;\n+import org.keycloak.testsuite.arquillian.AppServerTestEnricher;\nimport org.keycloak.testsuite.arquillian.AuthServerTestEnricher;\nimport org.keycloak.testsuite.arquillian.TestContext;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n@@ -39,6 +40,9 @@ public class AuthServerExcludeExecutionDecider implements TestExecutionDecider {\n@Override\npublic ExecutionDecision decide(Method method) {\n+ if (AppServerTestEnricher.isRemoteAppServer()) {\n+ return ExecutionDecision.execute();\n+ }\nTestContext testContext = testContextInstance.get();\nif (method.isAnnotationPresent(AuthServerContainerExclude.class)) {\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12964 Fix adapter remote tests execution deciding
339,167
11.02.2020 13:01:23
-3,600
1bdf77f40936611e963cd775f581fe2ed0aae8cf
UserSessionInitializerTest is failing
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractTestRealmKeycloakTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractTestRealmKeycloakTest.java", "diff": "@@ -21,6 +21,7 @@ import org.junit.After;\nimport org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.common.util.reflections.Reflections;\nimport org.keycloak.events.Details;\n+import org.keycloak.models.KeycloakSession;\nimport org.keycloak.representations.IDToken;\nimport org.keycloak.representations.idm.ClientRepresentation;\nimport org.keycloak.representations.idm.EventRepresentation;\n@@ -109,4 +110,9 @@ public abstract class AbstractTestRealmKeycloakTest extends AbstractKeycloakTest\nreturn idToken;\n}\n+ /** KEYCLOAK-12065 Inherit Client Connection from parent session **/\n+ public static KeycloakSession inheritClientConnection(KeycloakSession parentSession, KeycloakSession currentSession) {\n+ currentSession.getContext().setConnection(parentSession.getContext().getConnection());\n+ return currentSession;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java", "diff": "@@ -88,8 +88,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\nAtomicReference<UserSessionModel[]> origSessionsAtomic = new AtomicReference<>();\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInit1) -> {\n- KeycloakSession currentSession = SessionInit1;\n- UserSessionManager sessionManager = new UserSessionManager(currentSession);\n+ KeycloakSession currentSession = inheritClientConnection(session, SessionInit1);\nint started = Time.currentTime();\nstartedAtomic.set(started);\n@@ -103,7 +102,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\n});\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInit2) -> {\n- KeycloakSession currentSession = SessionInit2;\n+ KeycloakSession currentSession = inheritClientConnection(session, SessionInit2);\nRealmModel realm = currentSession.realms().getRealmByName(realmName);\nint started = startedAtomic.get();\n@@ -133,8 +132,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\nAtomicReference<UserSessionModel[]> origSessionsAtomic = new AtomicReference<>();\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInitWithDeleting1) -> {\n- KeycloakSession currentSession = SessionInitWithDeleting1;\n- UserSessionManager sessionManager = new UserSessionManager(currentSession);\n+ KeycloakSession currentSession = inheritClientConnection(session, SessionInitWithDeleting1);\nRealmModel realm = currentSession.realms().getRealmByName(realmName);\n@@ -149,7 +147,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\n});\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInitWithDeleting2) -> {\n- KeycloakSession currentSession = SessionInitWithDeleting2;\n+ KeycloakSession currentSession = inheritClientConnection(session, SessionInitWithDeleting2);\n// Load sessions from persister into infinispan/memory\nUserSessionProviderFactory userSessionFactory = (UserSessionProviderFactory) currentSession.getKeycloakSessionFactory().getProviderFactory(UserSessionProvider.class);\n@@ -157,7 +155,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\n});\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInitWithDeleting3) -> {\n- KeycloakSession currentSession = SessionInitWithDeleting3;\n+ KeycloakSession currentSession = inheritClientConnection(session, SessionInitWithDeleting3);\nRealmModel realm = currentSession.realms().getRealmByName(realmName);\nint started = startedAtomic.get();\n@@ -184,14 +182,14 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\nAtomicReference<UserSessionModel[]> origSessionsAtomic = new AtomicReference<>();\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister1) -> {\n- KeycloakSession currentSession = createSessionPersister1;\n+ KeycloakSession currentSession = inheritClientConnection(session, createSessionPersister1);\nUserSessionModel[] origSessions = createSessions(currentSession);\norigSessionsAtomic.set(origSessions);\n});\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister2) -> {\n- KeycloakSession currentSession = createSessionPersister2;\n+ KeycloakSession currentSession = inheritClientConnection(session, createSessionPersister2);\nRealmModel realm = currentSession.realms().getRealmByName(realmName);\nUserSessionManager sessionManager = new UserSessionManager(currentSession);\n@@ -206,7 +204,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\n});\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister3) -> {\n- KeycloakSession currentSession = createSessionPersister3;\n+ KeycloakSession currentSession = inheritClientConnection(session, createSessionPersister3);\nRealmModel realm = currentSession.realms().getRealmByName(realmName);\n// Delete cache (persisted sessions are still kept)\n@@ -219,7 +217,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {\n});\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister4) -> {\n- KeycloakSession currentSession = createSessionPersister4;\n+ KeycloakSession currentSession = inheritClientConnection(session, createSessionPersister4);\nRealmModel realm = currentSession.realms().getRealmByName(realmName);\nClientModel testApp = realm.getClientByClientId(\"test-app\");\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java", "diff": "@@ -259,6 +259,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest {\nRealmModel realm = session.realms().getRealmByName(\"test\");\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {\n+ inheritClientConnection(session, kcSession);\ncreateSessions(kcSession);\n});\nMap<String, Integer> clientSessionsKept = new HashMap<>();\n@@ -300,6 +301,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest {\npublic void testRemoveUserSessionsByRealm(KeycloakSession session) {\nRealmModel realm = session.realms().getRealmByName(\"test\");\nKeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {\n+ inheritClientConnection(session, kcSession);\ncreateSessions(kcSession);\n});\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12065 UserSessionInitializerTest is failing
339,167
12.02.2020 12:58:12
-3,600
90b35cc13d5ac9c8e785ecba1e7e94f50536cce8
Broker tests don't work with RH-SSO
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java", "diff": "@@ -142,7 +142,7 @@ public abstract class AbstractAdvancedBrokerTest extends AbstractBrokerTest {\ndriver.navigate().to(getAccountUrl(bc.consumerRealmName()));\nlogInWithBroker(bc);\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nlogoutFromRealm(bc.providerRealmName());\nlogoutFromRealm(bc.consumerRealmName());\n@@ -175,7 +175,7 @@ public abstract class AbstractAdvancedBrokerTest extends AbstractBrokerTest {\ndriver.navigate().to(getAccountUrl(bc.consumerRealmName()));\nlogInWithBroker(bc);\nupdatePasswordPage.updatePasswords(\"password\", \"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nString username = bc.getUserLogin();\n@@ -421,7 +421,7 @@ public abstract class AbstractAdvancedBrokerTest extends AbstractBrokerTest {\ndriver.getCurrentUrl().contains(\"/auth/realms/\" + bc.providerRealmName() + \"/\"));\nlog.debug(\"Logging in\");\nloginPage.login(bc.getUserLogin(), bc.getUserPassword());\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n@@ -475,7 +475,7 @@ public abstract class AbstractAdvancedBrokerTest extends AbstractBrokerTest {\ndriver.navigate().to(getAccountUrl(bc.consumerRealmName()));\nloginPage.clickSocial(bc.getIDPAlias());\nloginPage.login(\"test-user\", \"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\naccountPage.password();\n@@ -492,7 +492,7 @@ public abstract class AbstractAdvancedBrokerTest extends AbstractBrokerTest {\ndriver.navigate().to(getAccountUrl(bc.consumerRealmName()));\nloginPage.clickSocial(bc.getIDPAlias());\nloginPage.login(\"test-user-noemail\", \"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\naccountPage.password();\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java", "diff": "@@ -32,6 +32,8 @@ import org.keycloak.representations.idm.UserRepresentation;\nimport org.keycloak.services.resources.RealmsResource;\nimport org.keycloak.testsuite.AbstractKeycloakTest;\nimport org.keycloak.testsuite.Assert;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n+import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\nimport org.keycloak.testsuite.pages.AccountApplicationsPage;\nimport org.keycloak.testsuite.pages.AccountFederatedIdentityPage;\nimport org.keycloak.testsuite.pages.AccountPasswordPage;\n@@ -62,8 +64,6 @@ import static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertThat;\nimport static org.keycloak.testsuite.admin.ApiUtil.createUserWithAdminClient;\nimport static org.keycloak.testsuite.admin.ApiUtil.resetUserPassword;\n-import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\n-import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\nimport static org.keycloak.testsuite.broker.BrokerTestConstants.USER_EMAIL;\nimport static org.keycloak.testsuite.broker.BrokerTestTools.encodeUrl;\nimport static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage;\n@@ -275,12 +275,18 @@ public abstract class AbstractBaseBrokerTest extends AbstractKeycloakTest {\nprotected void assertLoggedInAccountManagement() {\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\nAssert.assertTrue(accountUpdateProfilePage.isCurrent());\nAssert.assertEquals(accountUpdateProfilePage.getUsername(), bc.getUserLogin());\nAssert.assertEquals(accountUpdateProfilePage.getEmail(), bc.getUserEmail());\n}\n+ protected void waitForAccountManagementTitle() {\n+ boolean isProduct = adminClient.serverInfo().getInfo().getProfileInfo().getName().equals(\"product\");\n+ String title = isProduct ? \"rh-sso account management\" : \"keycloak account management\";\n+ waitForPage(driver, title, true);\n+ }\n+\nprotected void assertErrorPage(String expectedError) {\nerrorPage.assertCurrent();\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java", "diff": "@@ -106,7 +106,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\n}\nloginPage.login(\"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertNumFederatedIdentities(existingUser, 1);\n@@ -177,7 +177,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\n// Use correct password now\nloginPage.login(\"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertNumFederatedIdentities(userId, 1);\n}\n@@ -229,7 +229,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nthis.passwordUpdatePage.assertCurrent();\nthis.passwordUpdatePage.changePassword(\"password\", \"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertNumFederatedIdentities(existingUser, 1);\n}\n@@ -309,7 +309,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\ndriver.navigate().to(getAccountUrl(bc.consumerRealmName()));\nlogInWithBroker(bc);\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n@@ -378,7 +378,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nwaitForPage(driver, \"update password\", false);\nupdatePasswordPage.updatePasswords(\"password\", \"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n@@ -420,7 +420,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nwaitForPage(driver, \"update account information\", false);\nAssert.assertTrue(updateAccountInformationPage.isCurrent());\nupdateAccountInformationPage.updateAccountInformation(\"test\", \"[email protected]\", \"FirstName\", \"LastName\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n@@ -456,7 +456,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nupdateAccountInformationPage.assertCurrent();\nupdateAccountInformationPage.updateAccountInformation(\"FirstName\", \"LastName\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\ntestingClient.server().run(assertHardCodedSessionNote());\n}\n@@ -490,7 +490,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\n}\nupdateAccountInformationPage.updateAccountInformation(\"[email protected]\", \"FirstName\", \"LastName\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertEquals(1, realm.users().search(\"[email protected]\").size());\n@@ -570,7 +570,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\n\"verify your email address\", false);\ndriver.navigate().to(verificationUrl.trim());\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n@@ -600,7 +600,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nlog.debug(\"Logging in\");\nloginPage.login(\"no-email\", \"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nList<UserRepresentation> users = realm.users().search(\"no-email\");\n@@ -637,7 +637,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nupdateAccountInformationPage.assertCurrent();\nupdateAccountInformationPage.updateAccountInformation(\"FirstName\", \"LastName\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nList<UserRepresentation> users = realm.users().search(bc.getUserLogin());\n@@ -680,7 +680,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\n\"verify your email address\", false);\ndriver.navigate().to(verificationUrl.trim());\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nList<UserRepresentation> users = realm.users().search(bc.getUserLogin());\n@@ -838,7 +838,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nwaitForPage(driver, \"update account information\", false);\nupdateAccountInformationPage.assertCurrent();\nupdateAccountInformationPage.updateAccountInformation(\"FirstName\", \"LastName\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nlogoutFromRealm(bc.providerRealmName());\n@@ -856,7 +856,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nwaitForPage(driver, \"update account information\", false);\nupdateAccountInformationPage.assertCurrent();\nupdateAccountInformationPage.updateAccountInformation(\"FirstName\", \"LastName\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nlogoutFromRealm(bc.providerRealmName());\n@@ -875,7 +875,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nupdateAccountInformationPage.assertCurrent();\nupdateAccountInformationPage.updateAccountInformation(\"[email protected]\", \"FirstName\", \"LastName\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n@@ -897,7 +897,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\nlog.debug(\"Logging in\");\nloginPage.login(\"all-info-set\", \"password\");\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n@@ -911,7 +911,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa\ndriver.navigate().to(getAccountUrl(bc.consumerRealmName()));\nlogInWithBroker(bc);\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java", "diff": "@@ -76,8 +76,7 @@ public class KcOidcBrokerLogoutTest extends AbstractBaseBrokerTest {\nlogoutFromRealm(bc.consumerRealmName(), \"kc-oidc-idp\");\ndriver.navigate().to(getAccountUrl(REALM_PROV_NAME));\n- //could be 'keycloak account management' or 'rh-sso account management'\n- waitForPage(driver, \" account management\", true);\n+ waitForAccountManagementTitle();\n}\n@Test\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptNoneRedirectTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptNoneRedirectTest.java", "diff": "@@ -70,7 +70,7 @@ public class KcOidcBrokerPromptNoneRedirectTest extends AbstractInitializedBaseB\n/* no need to log in again, the idp should have been able to identify that the user is already logged in and the authenticated user should\nhave been established in the consumer realm. Lastly, user must be redirected to the account app as expected. */\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\nAssert.assertTrue(driver.getCurrentUrl().contains(\"/auth/realms/\" + bc.consumerRealmName() + \"/account\"));\naccountUpdateProfilePage.assertCurrent();\n@@ -215,7 +215,7 @@ public class KcOidcBrokerPromptNoneRedirectTest extends AbstractInitializedBaseB\ndriver.getCurrentUrl().contains(\"/auth/realms/\" + bc.providerRealmName() + \"/\"));\nloginPage.login(bc.getUserLogin(), bc.getUserPassword());\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\nAssert.assertTrue(driver.getCurrentUrl().contains(\"/auth/realms/\" + bc.providerRealmName() + \"/account\"));\naccountUpdateProfilePage.assertCurrent();\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTest.java", "diff": "@@ -269,7 +269,7 @@ public final class KcOidcBrokerTest extends AbstractAdvancedBrokerTest {\nloginTotpPage.assertCurrent();\nloginTotpPage.login(totp.generateTOTP(totpSecret));\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertNumFederatedIdentities(consumerRealm.users().search(samlBrokerConfig.getUserLogin()).get(0).getId(), 2);\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java", "diff": "@@ -223,7 +223,7 @@ public class KcOidcFirstBrokerLoginNewAuthTest extends AbstractInitializedBaseBr\nprivate void assertUserAuthenticatedInConsumer(String consumerRealmUserId) {\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertNumFederatedIdentities(consumerRealmUserId, 1);\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginTest.java", "diff": "@@ -41,7 +41,7 @@ public class KcOidcFirstBrokerLoginTest extends AbstractFirstBrokerLoginTest {\ndriver.navigate().to(getAccountUrl(bc.consumerRealmName()));\nlogInWithBroker(samlBrokerConfig);\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nlogoutFromRealm(bc.consumerRealmName());\n@@ -62,7 +62,7 @@ public class KcOidcFirstBrokerLoginTest extends AbstractFirstBrokerLoginTest {\nlog.debug(\"Clicking social \" + samlBrokerConfig.getIDPAlias());\nloginPage.clickSocial(samlBrokerConfig.getIDPAlias());\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertNumFederatedIdentities(consumerRealm.users().search(samlBrokerConfig.getUserLogin()).get(0).getId(), 2);\n@@ -103,7 +103,7 @@ public class KcOidcFirstBrokerLoginTest extends AbstractFirstBrokerLoginTest {\n// User is federated after log in with the original broker\nlog.debug(\"Clicking social \" + samlBrokerConfig.getIDPAlias());\nloginPage.clickSocial(samlBrokerConfig.getIDPAlias());\n- waitForPage(driver, \"keycloak account management\", true);\n+ waitForAccountManagementTitle();\naccountUpdateProfilePage.assertCurrent();\nassertNumFederatedIdentities(consumerRealm.users().search(samlBrokerConfig.getUserLogin()).get(0).getId(), 1);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-10420 Broker tests don't work with RH-SSO
339,235
13.02.2020 15:08:40
-3,600
4b09a4a2af2fffaca8de4d181eff47f105d7c4da
AuthorizationBean invokes ResolveRelative.resolveRelativeUri with null as the value for KeycloakSession
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/forms/account/freemarker/model/AuthorizationBean.java", "new_path": "services/src/main/java/org/keycloak/forms/account/freemarker/model/AuthorizationBean.java", "diff": "@@ -49,6 +49,7 @@ import org.keycloak.services.util.ResolveRelative;\n*/\npublic class AuthorizationBean {\n+ private final KeycloakSession session;\nprivate final UserModel user;\nprivate final AuthorizationProvider authorization;\nprivate final UriInfo uriInfo;\n@@ -59,6 +60,7 @@ public class AuthorizationBean {\nprivate Collection<ResourceBean> resourcesWaitingOthersApproval;\npublic AuthorizationBean(KeycloakSession session, UserModel user, UriInfo uriInfo) {\n+ this.session = session;\nthis.user = user;\nthis.uriInfo = uriInfo;\nauthorization = session.getProvider(AuthorizationProvider.class);\n@@ -383,7 +385,7 @@ public class AuthorizationBean {\n}\npublic String getBaseUri() {\n- return ResolveRelative.resolveRelativeUri(null, clientModel.getRootUrl(), clientModel.getBaseUrl());\n+ return ResolveRelative.resolveRelativeUri(session, clientModel.getRootUrl(), clientModel.getBaseUrl());\n}\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12993 AuthorizationBean invokes ResolveRelative.resolveRelativeUri with null as the value for KeycloakSession
339,235
14.02.2020 10:52:36
-3,600
f0e31227928566a27c8a0a14d27f1c411c7dfce2
Ignore empty realm frontendUrl
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/url/DefaultHostnameProvider.java", "new_path": "services/src/main/java/org/keycloak/url/DefaultHostnameProvider.java", "diff": "@@ -97,7 +97,7 @@ public class DefaultHostnameProvider implements HostnameProvider {\nrealmUri = null;\nString realmFrontendUrl = session.getContext().getRealm().getAttribute(\"frontendUrl\");\n- if (realmFrontendUrl != null) {\n+ if (realmFrontendUrl != null && !realmFrontendUrl.isEmpty()) {\ntry {\nrealmUri = new URI(realmFrontendUrl);\n} catch (URISyntaxException e) {\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/url/DefaultHostnameTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/url/DefaultHostnameTest.java", "diff": "@@ -9,6 +9,7 @@ import org.jboss.arquillian.test.api.ArquillianResource;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.keycloak.admin.client.Keycloak;\n+import org.keycloak.admin.client.resource.RealmResource;\nimport org.keycloak.broker.provider.util.SimpleHttp;\nimport org.keycloak.client.registration.Auth;\nimport org.keycloak.client.registration.ClientRegistration;\n@@ -99,6 +100,26 @@ public class DefaultHostnameTest extends AbstractHostnameTest {\n}\n}\n+ // KEYCLOAK-12953\n+ @Test\n+ public void emptyRealmFrontendUrl() throws URISyntaxException {\n+ expectedBackendUrl = AUTH_SERVER_ROOT;\n+ oauth.clientId(\"direct-grant\");\n+\n+ RealmResource realmResource = realmsResouce().realm(\"frontendUrl\");\n+ RealmRepresentation rep = realmResource.toRepresentation();\n+\n+ try {\n+ rep.getAttributes().put(\"frontendUrl\", \"\");\n+ realmResource.update(rep);\n+\n+ assertWellKnown(\"frontendUrl\", AUTH_SERVER_ROOT);\n+ } finally {\n+ rep.getAttributes().put(\"frontendUrl\", realmFrontEndUrl);\n+ realmResource.update(rep);\n+ }\n+ }\n+\n@Test\npublic void fixedAdminUrl() throws Exception {\nexpectedBackendUrl = AUTH_SERVER_ROOT;\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12953 Ignore empty realm frontendUrl
339,465
12.02.2020 08:44:23
-3,600
a76c496c23d7294f39933db3b7a31fee62490e87
KEYCLOAK-12875 Fix for Account REST Credentials to work with LDAP and social users
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/authentication/AuthenticationSelectionOption.java", "new_path": "server-spi-private/src/main/java/org/keycloak/authentication/AuthenticationSelectionOption.java", "diff": "@@ -2,6 +2,7 @@ package org.keycloak.authentication;\nimport org.keycloak.credential.CredentialProvider;\nimport org.keycloak.credential.CredentialTypeMetadata;\n+import org.keycloak.credential.CredentialTypeMetadataContext;\nimport org.keycloak.models.AuthenticationExecutionModel;\nimport org.keycloak.models.KeycloakSession;\n@@ -15,7 +16,10 @@ public class AuthenticationSelectionOption {\nAuthenticator authenticator = session.getProvider(Authenticator.class, authExec.getAuthenticator());\nif (authenticator instanceof CredentialValidator) {\nCredentialProvider credentialProvider = ((CredentialValidator) authenticator).getCredentialProvider(session);\n- credentialTypeMetadata = credentialProvider.getCredentialTypeMetadata();\n+\n+ CredentialTypeMetadataContext ctx = CredentialTypeMetadataContext.builder()\n+ .build(session);\n+ credentialTypeMetadata = credentialProvider.getCredentialTypeMetadata(ctx);\n} else {\ncredentialTypeMetadata = null;\n}\n" }, { "change_type": "MODIFY", "old_path": "server-spi/src/main/java/org/keycloak/credential/CredentialProvider.java", "new_path": "server-spi/src/main/java/org/keycloak/credential/CredentialProvider.java", "diff": "@@ -50,5 +50,5 @@ public interface CredentialProvider<T extends CredentialModel> extends Provider\nreturn getCredentialFromModel(models.get(0));\n}\n- CredentialTypeMetadata getCredentialTypeMetadata();\n+ CredentialTypeMetadata getCredentialTypeMetadata(CredentialTypeMetadataContext metadataContext);\n}\n" }, { "change_type": "MODIFY", "old_path": "server-spi/src/main/java/org/keycloak/credential/CredentialTypeMetadata.java", "new_path": "server-spi/src/main/java/org/keycloak/credential/CredentialTypeMetadata.java", "diff": "@@ -50,7 +50,7 @@ public class CredentialTypeMetadata implements Comparable<CredentialTypeMetadata\npublic enum Category {\n- PASSWORD(\"password\", 1),\n+ BASIC_AUTHENTICATION(\"basic-authentication\", 1),\nTWO_FACTOR(\"two-factor\", 2),\nPASSWORDLESS(\"passwordless\", 3);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server-spi/src/main/java/org/keycloak/credential/CredentialTypeMetadataContext.java", "diff": "+/*\n+ * Copyright 2019 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+\n+package org.keycloak.credential;\n+\n+import org.keycloak.models.KeycloakSession;\n+import org.keycloak.models.UserModel;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Marek Posolda</a>\n+ */\n+public class CredentialTypeMetadataContext {\n+\n+ private UserModel user;\n+\n+ private CredentialTypeMetadataContext() {\n+ }\n+\n+ /**\n+ * @return user, for which we create metadata. Could be null\n+ */\n+ public UserModel getUser() {\n+ return user;\n+ }\n+\n+ public static CredentialTypeMetadataContext.CredentialTypeMetadataContextBuilder builder() {\n+ return new CredentialTypeMetadataContext.CredentialTypeMetadataContextBuilder();\n+ }\n+\n+ // BUILDER\n+\n+ public static class CredentialTypeMetadataContextBuilder {\n+\n+ private CredentialTypeMetadataContext instance = new CredentialTypeMetadataContext();\n+\n+ public CredentialTypeMetadataContext.CredentialTypeMetadataContextBuilder user(UserModel user) {\n+ instance.user = user;\n+ return this;\n+ }\n+\n+ public CredentialTypeMetadataContext build(KeycloakSession session) {\n+ // Possible to have null user\n+ return instance;\n+ }\n+\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java", "new_path": "services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java", "diff": "@@ -142,7 +142,7 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo\n}\n@Override\n- public CredentialTypeMetadata getCredentialTypeMetadata() {\n+ public CredentialTypeMetadata getCredentialTypeMetadata(CredentialTypeMetadataContext metadataContext) {\nreturn CredentialTypeMetadata.builder()\n.type(getType())\n.category(CredentialTypeMetadata.Category.TWO_FACTOR)\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java", "new_path": "services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java", "diff": "package org.keycloak.credential;\nimport org.jboss.logging.Logger;\n-import org.keycloak.authentication.requiredactions.WebAuthnRegisterFactory;\nimport org.keycloak.common.util.Time;\nimport org.keycloak.credential.hash.PasswordHashProvider;\nimport org.keycloak.models.ModelException;\n@@ -296,14 +295,23 @@ public class PasswordCredentialProvider implements CredentialProvider<PasswordCr\n}\n@Override\n- public CredentialTypeMetadata getCredentialTypeMetadata() {\n- return CredentialTypeMetadata.builder()\n+ public CredentialTypeMetadata getCredentialTypeMetadata(CredentialTypeMetadataContext metadataContext) {\n+ CredentialTypeMetadata.CredentialTypeMetadataBuilder metadataBuilder = CredentialTypeMetadata.builder()\n.type(getType())\n- .category(CredentialTypeMetadata.Category.PASSWORD)\n- .displayName(\"password\")\n+ .category(CredentialTypeMetadata.Category.BASIC_AUTHENTICATION)\n+ .displayName(\"password-display-name\")\n.helpText(\"password-help-text\")\n- .iconCssClass(\"kcAuthenticatorPasswordClass\")\n- .updateAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString())\n+ .iconCssClass(\"kcAuthenticatorPasswordClass\");\n+\n+ // Check if we are creating or updating password\n+ UserModel user = metadataContext.getUser();\n+ if (user != null && session.userCredentialManager().isConfiguredFor(session.getContext().getRealm(), user, getType())) {\n+ metadataBuilder.updateAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString());\n+ } else {\n+ metadataBuilder.createAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString());\n+ }\n+\n+ return metadataBuilder\n.removeable(false)\n.build(session);\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/credential/WebAuthnCredentialProvider.java", "new_path": "services/src/main/java/org/keycloak/credential/WebAuthnCredentialProvider.java", "diff": "@@ -230,7 +230,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr\n}\n@Override\n- public CredentialTypeMetadata getCredentialTypeMetadata() {\n+ public CredentialTypeMetadata getCredentialTypeMetadata(CredentialTypeMetadataContext metadataContext) {\nreturn CredentialTypeMetadata.builder()\n.type(getType())\n.category(CredentialTypeMetadata.Category.TWO_FACTOR)\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/credential/WebAuthnPasswordlessCredentialProvider.java", "new_path": "services/src/main/java/org/keycloak/credential/WebAuthnPasswordlessCredentialProvider.java", "diff": "@@ -40,7 +40,7 @@ public class WebAuthnPasswordlessCredentialProvider extends WebAuthnCredentialPr\n}\n@Override\n- public CredentialTypeMetadata getCredentialTypeMetadata() {\n+ public CredentialTypeMetadata getCredentialTypeMetadata(CredentialTypeMetadataContext metadataContext) {\nreturn CredentialTypeMetadata.builder()\n.type(getType())\n.category(CredentialTypeMetadata.Category.PASSWORDLESS)\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/account/AccountCredentialResource.java", "new_path": "services/src/main/java/org/keycloak/services/resources/account/AccountCredentialResource.java", "diff": "@@ -7,6 +7,7 @@ import org.keycloak.authentication.AuthenticatorFactory;\nimport org.keycloak.credential.CredentialModel;\nimport org.keycloak.credential.CredentialProvider;\nimport org.keycloak.credential.CredentialTypeMetadata;\n+import org.keycloak.credential.CredentialTypeMetadataContext;\nimport org.keycloak.credential.PasswordCredentialProvider;\nimport org.keycloak.credential.PasswordCredentialProviderFactory;\nimport org.keycloak.credential.UserCredentialStoreManager;\n@@ -31,6 +32,7 @@ import javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.Response;\nimport java.io.IOException;\n+import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.LinkedList;\n@@ -185,13 +187,29 @@ public class AccountCredentialResource {\ncontinue;\n}\n- CredentialTypeMetadata metadata = credentialProvider.getCredentialTypeMetadata();\n+ CredentialTypeMetadataContext ctx = CredentialTypeMetadataContext.builder()\n+ .user(user)\n+ .build(session);\n+ CredentialTypeMetadata metadata = credentialProvider.getCredentialTypeMetadata(ctx);\nList<CredentialRepresentation> userCredentialModels = filterUserCredentials ? null : models.stream()\n.filter(credentialModel -> credentialProvider.getType().equals(credentialModel.getType()))\n.map(ModelToRepresentation::toRepresentation)\n.collect(Collectors.toList());\n+ if (userCredentialModels != null && userCredentialModels.isEmpty() &&\n+ session.userCredentialManager().isConfiguredFor(realm, user, credentialProviderType)) {\n+ // In case user is federated in the userStorage, he may have credential configured on the userStorage side. We're\n+ // creating \"dummy\" credential representing the credential provided by userStorage\n+ CredentialRepresentation credential = new CredentialRepresentation();\n+ credential.setId(credentialProviderType + \"-id\");\n+ credential.setType(credentialProviderType);\n+ credential.setCreatedDate(-1L);\n+ credential.setPriority(0);\n+\n+ userCredentialModels = Collections.singletonList(credential);\n+ }\n+\nCredentialContainer credType = new CredentialContainer(metadata, userCredentialModels);\ncredentialTypes.add(credType);\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/resources/org/keycloak/testsuite/integration-arquillian-testsuite-providers/main/module.xml", "new_path": "testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/resources/org/keycloak/testsuite/integration-arquillian-testsuite-providers/main/module.xml", "diff": "<resource-root path=\"integration-arquillian-testsuite-providers-${project.version}.jar\"/>\n</resources>\n<dependencies>\n+ <module name=\"com.fasterxml.jackson.core.jackson-core\"/>\n<module name=\"javax.api\"/>\n<module name=\"javax.ws.rs.api\"/>\n<module name=\"javax.servlet.api\"/>\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceTest.java", "diff": "@@ -20,10 +20,10 @@ import com.fasterxml.jackson.core.type.TypeReference;\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.keycloak.OAuth2Constants;\n+import org.keycloak.admin.client.resource.UserResource;\nimport org.keycloak.authentication.authenticators.browser.WebAuthnAuthenticatorFactory;\nimport org.keycloak.authentication.authenticators.browser.WebAuthnPasswordlessAuthenticatorFactory;\nimport org.keycloak.authentication.requiredactions.WebAuthnPasswordlessRegisterFactory;\n-import org.keycloak.authentication.requiredactions.WebAuthnRegister;\nimport org.keycloak.authentication.requiredactions.WebAuthnRegisterFactory;\nimport org.keycloak.broker.provider.util.SimpleHttp;\nimport org.keycloak.credential.CredentialTypeMetadata;\n@@ -45,7 +45,6 @@ import org.keycloak.representations.idm.AuthenticationFlowRepresentation;\nimport org.keycloak.representations.idm.ClientScopeRepresentation;\nimport org.keycloak.representations.idm.CredentialRepresentation;\nimport org.keycloak.representations.idm.ErrorRepresentation;\n-import org.keycloak.representations.idm.EventRepresentation;\nimport org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.representations.idm.RequiredActionProviderRepresentation;\nimport org.keycloak.representations.idm.RequiredActionProviderSimpleRepresentation;\n@@ -70,7 +69,6 @@ import static org.junit.Assert.*;\nimport org.keycloak.services.resources.account.AccountCredentialResource.PasswordUpdate;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;\nimport org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;\n-import org.keycloak.testsuite.util.WaitUtils;\n/**\n* @author <a href=\"mailto:[email protected]\">Stian Thorgersen</a>\n@@ -91,6 +89,7 @@ public class AccountRestServiceTest extends AbstractRestServiceTest {\n@Test\npublic void testUpdateProfile() throws IOException {\nUserRepresentation user = SimpleHttp.doGet(getAccountUrl(null), httpClient).auth(tokenUtil.getToken()).asJson(UserRepresentation.class);\n+ String originalUsername = user.getUsername();\nString originalFirstName = user.getFirstName();\nString originalLastName = user.getLastName();\nString originalEmail = user.getEmail();\n@@ -157,6 +156,7 @@ public class AccountRestServiceTest extends AbstractRestServiceTest {\nrealmRep.setEditUsernameAllowed(true);\nadminClient.realm(\"test\").update(realmRep);\n+ user.setUsername(originalUsername);\nuser.setFirstName(originalFirstName);\nuser.setLastName(originalLastName);\nuser.setEmail(originalEmail);\n@@ -316,8 +316,8 @@ public class AccountRestServiceTest extends AbstractRestServiceTest {\nAssert.assertEquals(4, credentials.size());\nAccountCredentialResource.CredentialContainer password = credentials.get(0);\n- assertCredentialContainerExpected(password, PasswordCredentialModel.TYPE, CredentialTypeMetadata.Category.PASSWORD.toString(),\n- \"password\", \"password-help-text\", \"kcAuthenticatorPasswordClass\",\n+ assertCredentialContainerExpected(password, PasswordCredentialModel.TYPE, CredentialTypeMetadata.Category.BASIC_AUTHENTICATION.toString(),\n+ \"password-display-name\", \"password-help-text\", \"kcAuthenticatorPasswordClass\",\nnull, UserModel.RequiredAction.UPDATE_PASSWORD.toString(), false, 1);\nCredentialRepresentation password1 = password.getUserCredentials().get(0);\n@@ -443,6 +443,32 @@ public class AccountRestServiceTest extends AbstractRestServiceTest {\n}\n}\n+ @Test\n+ public void testCredentialsForUserWithoutPassword() throws IOException {\n+ // This is just to call REST to ensure tokenUtil will authenticate user and create the tokens.\n+ // We won't be able to authenticate later as user won't have password\n+ List<AccountCredentialResource.CredentialContainer> credentials = getCredentials();\n+\n+ // Remove password from the user now\n+ UserResource user = ApiUtil.findUserByUsernameId(testRealm(), \"test-user@localhost\");\n+ for (CredentialRepresentation credential : user.credentials()) {\n+ if (PasswordCredentialModel.TYPE.equals(credential.getType())) {\n+ user.removeCredential(credential.getId());\n+ }\n+ }\n+\n+ // Get credentials. Ensure user doesn't have password credential and create action is UPDATE_PASSWORD\n+ credentials = getCredentials();\n+ AccountCredentialResource.CredentialContainer password = credentials.get(0);\n+ assertCredentialContainerExpected(password, PasswordCredentialModel.TYPE, CredentialTypeMetadata.Category.BASIC_AUTHENTICATION.toString(),\n+ \"password-display-name\", \"password-help-text\", \"kcAuthenticatorPasswordClass\",\n+ UserModel.RequiredAction.UPDATE_PASSWORD.toString(), null, false, 0);\n+\n+ // Re-add the password to the user\n+ ApiUtil.resetUserPassword(user, \"password\", false);\n+\n+ }\n+\n// Sets new requirement and returns current requirement\nprivate AuthenticationExecutionModel.Requirement setExecutionRequirement(String flowAlias, String executionDisplayName, AuthenticationExecutionModel.Requirement newRequirement) {\nList<AuthenticationExecutionInfoRepresentation> executionInfos = testRealm().flows().getExecutions(flowAlias);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAccountRestApiTest.java", "diff": "+/*\n+ * Copyright 2019 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+\n+package org.keycloak.testsuite.federation.ldap;\n+\n+import java.io.IOException;\n+import java.util.List;\n+\n+import com.fasterxml.jackson.core.type.TypeReference;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.impl.client.HttpClientBuilder;\n+import org.junit.After;\n+import org.junit.Assert;\n+import org.junit.Before;\n+import org.junit.ClassRule;\n+import org.junit.FixMethodOrder;\n+import org.junit.Rule;\n+import org.junit.Test;\n+import org.junit.runners.MethodSorters;\n+import org.keycloak.broker.provider.util.SimpleHttp;\n+import org.keycloak.models.RealmModel;\n+import org.keycloak.models.credential.PasswordCredentialModel;\n+import org.keycloak.representations.account.UserRepresentation;\n+import org.keycloak.representations.idm.CredentialRepresentation;\n+import org.keycloak.services.resources.account.AccountCredentialResource;\n+import org.keycloak.storage.ldap.idm.model.LDAPObject;\n+import org.keycloak.testsuite.arquillian.annotation.EnableFeature;\n+import org.keycloak.testsuite.util.LDAPRule;\n+import org.keycloak.testsuite.util.LDAPTestUtils;\n+import org.keycloak.testsuite.util.TokenUtil;\n+\n+import static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertFalse;\n+import static org.keycloak.common.Profile.Feature.ACCOUNT_API;\n+\n+/**\n+ * @author <a href=\"mailto:[email protected]\">Marek Posolda</a>\n+ */\n+@EnableFeature(value = ACCOUNT_API, skipRestart = true)\n+@FixMethodOrder(MethodSorters.NAME_ASCENDING)\n+public class LDAPAccountRestApiTest extends AbstractLDAPTest {\n+\n+ @Rule\n+ public TokenUtil tokenUtil = new TokenUtil(\"johnkeycloak\", \"Password1\");\n+\n+ @ClassRule\n+ public static LDAPRule ldapRule = new LDAPRule();\n+\n+ protected CloseableHttpClient httpClient;\n+\n+ @Before\n+ public void before() {\n+ httpClient = HttpClientBuilder.create().build();\n+ }\n+\n+ @After\n+ public void after() {\n+ try {\n+ httpClient.close();\n+ } catch (IOException e) {\n+ throw new RuntimeException(e);\n+ }\n+ }\n+\n+ @Override\n+ protected LDAPRule getLDAPRule() {\n+ return ldapRule;\n+ }\n+\n+ @Override\n+ protected void afterImportTestRealm() {\n+ testingClient.server().run(session -> {\n+ LDAPTestContext ctx = LDAPTestContext.init(session);\n+ RealmModel appRealm = ctx.getRealm();\n+\n+ // Delete all LDAP users and add some new for testing\n+ LDAPTestUtils.removeAllLDAPUsers(ctx.getLdapProvider(), appRealm);\n+\n+ LDAPObject john = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, \"johnkeycloak\", \"John\", \"Doe\", \"[email protected]\", null, \"1234\");\n+ LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), john, \"Password1\");\n+ });\n+ }\n+\n+ @Test\n+ public void testGetProfile() throws IOException {\n+ UserRepresentation user = SimpleHttp.doGet(getAccountUrl(null), httpClient).auth(tokenUtil.getToken()).asJson(UserRepresentation.class);\n+ assertEquals(\"John\", user.getFirstName());\n+ assertEquals(\"Doe\", user.getLastName());\n+ assertEquals(\"[email protected]\", user.getEmail());\n+ assertFalse(user.isEmailVerified());\n+ }\n+\n+ @Test\n+ public void testGetCredentials() throws IOException {\n+ List<AccountCredentialResource.CredentialContainer> credentials = getCredentials();\n+\n+ AccountCredentialResource.CredentialContainer password = credentials.get(0);\n+ Assert.assertEquals(PasswordCredentialModel.TYPE, password.getType());\n+ Assert.assertEquals(1, password.getUserCredentials().size());\n+ CredentialRepresentation userPassword = password.getUserCredentials().get(0);\n+\n+ // Password won't have createdDate and any metadata set\n+ Assert.assertEquals(PasswordCredentialModel.TYPE, userPassword.getType());\n+ Assert.assertEquals(userPassword.getCreatedDate(), new Long(-1L));\n+ Assert.assertNull(userPassword.getCredentialData());\n+ Assert.assertNull(userPassword.getSecretData());\n+ }\n+\n+ private String getAccountUrl(String resource) {\n+ return suiteContext.getAuthServerInfo().getContextRoot().toString() + \"/auth/realms/test/account\" + (resource != null ? \"/\" + resource : \"\");\n+ }\n+\n+ // Send REST request to get all credential containers and credentials of current user\n+ private List<AccountCredentialResource.CredentialContainer> getCredentials() throws IOException {\n+ return SimpleHttp.doGet(getAccountUrl(\"credentials\"), httpClient)\n+ .auth(tokenUtil.getToken()).asJson(new TypeReference<List<AccountCredentialResource.CredentialContainer>>() {});\n+ }\n+\n+\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/other/base-ui/src/test/java/org/keycloak/testsuite/ui/account2/SigningInTest.java", "new_path": "testsuite/integration-arquillian/tests/other/base-ui/src/test/java/org/keycloak/testsuite/ui/account2/SigningInTest.java", "diff": "@@ -36,6 +36,7 @@ import org.keycloak.representations.idm.RealmRepresentation;\nimport org.keycloak.representations.idm.RequiredActionProviderRepresentation;\nimport org.keycloak.representations.idm.RequiredActionProviderSimpleRepresentation;\nimport org.keycloak.testsuite.WebAuthnAssume;\n+import org.keycloak.testsuite.admin.Users;\nimport org.keycloak.testsuite.auth.page.login.OTPSetup;\nimport org.keycloak.testsuite.auth.page.login.UpdatePassword;\nimport org.keycloak.testsuite.pages.webauthn.WebAuthnRegisterPage;\n@@ -62,7 +63,7 @@ import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad;\n* @author Vaclav Muzikar <[email protected]>\n*/\npublic class SigningInTest extends BaseAccountPageTest {\n- public static final String PASSWORD_LABEL = \"Password\";\n+ public static final String PASSWORD_LABEL = \"My Password\";\npublic static final String WEBAUTHN_FLOW_ID = \"75e2390e-f296-49e6-acf8-6d21071d7e10\";\n@Page\n@@ -148,7 +149,7 @@ public class SigningInTest extends BaseAccountPageTest {\nassertEquals(3, signingInPage.getCategoriesCount());\n- assertEquals(\"Password\", signingInPage.getCategoryTitle(\"password\"));\n+ assertEquals(\"Basic Authentication\", signingInPage.getCategoryTitle(\"basic-authentication\"));\nassertEquals(\"Two-Factor Authentication\", signingInPage.getCategoryTitle(\"two-factor\"));\nassertEquals(\"Passwordless\", signingInPage.getCategoryTitle(\"passwordless\"));\n@@ -180,8 +181,35 @@ public class SigningInTest extends BaseAccountPageTest {\nassertUserCredential(PASSWORD_LABEL, false, passwordCred);\nassertNotEquals(previousCreatedAt, passwordCred.getCreatedAt());\n+ }\n+\n+ @Test\n+ public void updatePasswordTestForUserWithoutPassword() {\n+ // Remove password from the user through admin REST API\n+ String passwordId = testUserResource().credentials().get(0).getId();\n+ testUserResource().removeCredential(passwordId);\n+\n+ // Refresh the page\n+ refreshPageAndWaitForLoad();\n+\n+ // Test user doesn't have password set\n+ assertTrue(passwordCredentialType.isSetUpLinkVisible());\n+ assertFalse(passwordCredentialType.isSetUp());\n- // TODO KEYCLOAK-12875 try to update/set up password when user has no password configured\n+ // Set password\n+ passwordCredentialType.clickSetUpLink();\n+ updatePasswordPage.assertCurrent();\n+ String originalPassword = Users.getPasswordOf(testUser);\n+ updatePasswordPage.updatePasswords(originalPassword, originalPassword);\n+ // TODO uncomment this once KEYCLOAK-12852 is resolved\n+ // signingInPage.assertCurrent();\n+\n+ // Credential set-up now\n+ assertFalse(passwordCredentialType.isSetUpLinkVisible());\n+ assertTrue(passwordCredentialType.isSetUp());\n+ SigningInPage.UserCredential passwordCred =\n+ passwordCredentialType.getUserCredential(testUserResource().credentials().get(0).getId());\n+ assertUserCredential(PASSWORD_LABEL, false, passwordCred);\n}\n@Test\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/base/login/messages/messages_en.properties", "new_path": "themes/src/main/resources/theme/base/login/messages/messages_en.properties", "diff": "@@ -342,6 +342,7 @@ saml.post-form.js-disabled=JavaScript is disabled. We strongly recommend to enab\n#authenticators\notp-display-name=Authenticator Application\notp-help-text=Enter a verification code from authenticator application.\n+password-display-name=Password\npassword-help-text=Log in by entering your password.\nauth-username-form-display-name=Username\nauth-username-form-help-text=Start log in by entering your username\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak-preview/account/messages/messages_en.properties", "new_path": "themes/src/main/resources/theme/keycloak-preview/account/messages/messages_en.properties", "diff": "@@ -68,6 +68,9 @@ notSetUp={0} is not set up.\ntwo-factor=Two-Factor Authentication\npasswordless=Passwordless\nunknown=Unknown\n+password-display-name=Password\n+password-help-text=Log in by entering your password.\n+password=My Password\notp-display-name=Authenticator Application\notp-help-text=Enter a verification code from authenticator application.\nwebauthn-display-name=Security Key\n@@ -75,7 +78,6 @@ webauthn-help-text=Use your security key to log in.\nwebauthn-passwordless-display-name=Security Key\nwebauthn-passwordless-help-text=Use your security key for passwordless log in.\nbasic-authentication=Basic Authentication\n-basic-auth-help-text=Sign in with username and password.\n# Applications page\napplicationsPageTitle=Applications\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12860 KEYCLOAK-12875 Fix for Account REST Credentials to work with LDAP and social users
339,519
10.02.2020 14:38:34
10,800
497787d2cdbfd48ca40d605ef2206613c932e130
fixed missing client role attributes after import
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/models/utils/RepresentationToModel.java", "new_path": "server-spi-private/src/main/java/org/keycloak/models/utils/RepresentationToModel.java", "diff": "@@ -628,6 +628,9 @@ public class RepresentationToModel {\n// Application role may already exists (for example if it is defaultRole)\nRoleModel role = roleRep.getId() != null ? client.addRole(roleRep.getId(), roleRep.getName()) : client.addRole(roleRep.getName());\nrole.setDescription(roleRep.getDescription());\n+ if (roleRep.getAttributes() != null) {\n+ roleRep.getAttributes().forEach((key, value) -> role.setAttribute(key, value));\n+ }\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportTest.java", "diff": "@@ -315,6 +315,7 @@ public class ExportImportTest extends AbstractKeycloakTest {\nMap<String, List<String>> roleAttributes = adminClient.realm(\"test\").roles().get(\"attribute-role\").toRepresentation().getAttributes();\nString testAppId = adminClient.realm(\"test\").clients().findByClientId(\"test-app\").get(0).getId();\nString sampleClientRoleId = adminClient.realm(\"test\").clients().get(testAppId).roles().get(\"sample-client-role\").toRepresentation().getId();\n+ String sampleClientRoleAttribute = adminClient.realm(\"test\").clients().get(testAppId).roles().get(\"sample-client-role\").toRepresentation().getAttributes().get(\"sample-client-role-attribute\").get(0);\n// Delete some realm (and some data in admin realm)\nadminClient.realm(\"test\").remove();\n@@ -365,6 +366,9 @@ public class ExportImportTest extends AbstractKeycloakTest {\nString importedSampleClientRoleId = adminClient.realm(\"test\").clients().get(testAppId).roles().get(\"sample-client-role\").toRepresentation().getId();\nassertEquals(sampleClientRoleId, importedSampleClientRoleId);\n+ String importedSampleClientRoleAttribute = adminClient.realm(\"test\").clients().get(testAppId).roles().get(\"sample-client-role\").toRepresentation().getAttributes().get(\"sample-client-role-attribute\").get(0);\n+ assertEquals(sampleClientRoleAttribute, importedSampleClientRoleAttribute);\n+\ncheckEventsConfig(adminClient.realm(\"test\").getRealmEventsConfig());\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/resources/testrealm.json", "new_path": "testsuite/integration-arquillian/tests/base/src/test/resources/testrealm.json", "diff": "},\n{\n\"name\": \"sample-client-role\",\n- \"description\": \"Sample client role\"\n+ \"description\": \"Sample client role\",\n+ \"attributes\": {\n+ \"sample-client-role-attribute\": [\n+ \"sample-client-role-attribute-value\"\n+ ]\n+ }\n},\n{\n\"name\": \"customer-admin-composite-role\",\n" } ]
Java
Apache License 2.0
keycloak/keycloak
[KEYCLOAK-10696] - fixed missing client role attributes after import
339,192
14.02.2020 15:20:44
-32,400
21b12c39bd4508e9c69e7633b64a051fb95d9170
Remove a mention about providers directory
[ { "change_type": "MODIFY", "old_path": "examples/providers/rest/README.md", "new_path": "examples/providers/rest/README.md", "diff": "Example Realm REST Resource provider\n====================================\n-To deploy copy target/hello-rest-example.jar to providers directory. Alternatively you can deploy as a module by running:\n+You can deploy as a module by running:\n$KEYCLOAK_HOME/bin/jboss-cli.sh --command=\"module add --name=org.keycloak.examples.hello-rest-example --resources=target/hello-rest-example.jar --dependencies=org.keycloak.keycloak-core,org.keycloak.keycloak-server-spi,org.keycloak.keycloak-server-spi-private,javax.ws.rs.api\"\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-13003 Remove a mention about providers directory
339,465
10.02.2020 21:38:46
-3,600
eeeaafb5e7c7ae253bd2481c4837d1eb59bdcfcf
Authenticator is sometimes required even when configured as alternative
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/DefaultAuthenticationFlow.java", "new_path": "services/src/main/java/org/keycloak/authentication/DefaultAuthenticationFlow.java", "diff": "@@ -32,6 +32,7 @@ import javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.core.Response;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n+import java.util.LinkedList;\nimport java.util.List;\nimport java.util.stream.Collectors;\n@@ -187,76 +188,6 @@ public class DefaultAuthenticationFlow implements AuthenticationFlow {\n}\n- /**\n- * Clear execution status of targetExecution and also clear execution status of all the executions, which were triggered after this execution.\n- * This covers also \"flow\" executions and executions, which were set automatically\n- *\n- * @param targetExecution\n- */\n- private void recursiveClearExecutionStatusOfAllExecutionsAfterOurExecutionInclusive(AuthenticationExecutionModel targetExecution) {\n- RealmModel realm = processor.getRealm();\n- AuthenticationSessionModel authSession = processor.getAuthenticationSession();\n-\n- // Clear execution status of our execution\n- authSession.getExecutionStatus().remove(targetExecution.getId());\n-\n- // Find all the \"sibling\" executions after target execution including target execution. For those, we can recursively remove execution status\n- recursiveClearExecutionStatusOfAllSiblings(targetExecution);\n-\n- // Find the parent flow. If corresponding execution of this parent flow already has \"executionStatus\" set, we should clear it and also clear\n- // the status for all the siblings after that execution\n- while (true) {\n- AuthenticationFlowModel parentFlow = realm.getAuthenticationFlowById(targetExecution.getParentFlow());\n- if (parentFlow.isTopLevel()) {\n- return;\n- }\n-\n- AuthenticationExecutionModel flowExecution = realm.getAuthenticationExecutionByFlowId(parentFlow.getId());\n- if (authSession.getExecutionStatus().containsKey(flowExecution.getId())) {\n- authSession.getExecutionStatus().remove(flowExecution.getId());\n- recursiveClearExecutionStatusOfAllSiblings(flowExecution);\n- targetExecution = flowExecution;\n- } else {\n- return;\n- }\n-\n- }\n- }\n-\n-\n- /**\n- * Recursively removes the execution status of all \"sibling\" executions after targetExecution.\n- *\n- * @param targetExecution\n- */\n- private void recursiveClearExecutionStatusOfAllSiblings(AuthenticationExecutionModel targetExecution) {\n- RealmModel realm = processor.getRealm();\n- AuthenticationFlowModel parentFlow = realm.getAuthenticationFlowById(targetExecution.getParentFlow());\n-\n- logger.debugf(\"Recursively clearing executions in flow '%s', which are after execution '%s'\", parentFlow.getAlias(), targetExecution.getId());\n-\n- List<AuthenticationExecutionModel> siblingExecutions = realm.getAuthenticationExecutions(parentFlow.getId());\n- int index = siblingExecutions.indexOf(targetExecution);\n- siblingExecutions = siblingExecutions.subList(index + 1, siblingExecutions.size());\n-\n- for (AuthenticationExecutionModel authExec : siblingExecutions) {\n- recursiveClearExecutionStatus(authExec);\n- }\n- }\n-\n-\n- /**\n- * Removes the execution status for an execution. If it is a flow, do the same for all sub-executions.\n- *\n- * @param execution the execution for which the status must be cleared\n- */\n- private void recursiveClearExecutionStatus(AuthenticationExecutionModel execution) {\n- processor.getAuthenticationSession().getExecutionStatus().remove(execution.getId());\n- if (execution.isAuthenticatorFlow()) {\n- processor.getRealm().getAuthenticationExecutions(execution.getFlowId()).forEach(this::recursiveClearExecutionStatus);\n- }\n- }\n-\n/**\n* This method makes sure that the parent flow's corresponding execution is considered successful if its contained\n* executions are successful.\n@@ -270,9 +201,16 @@ public class DefaultAuthenticationFlow implements AuthenticationFlow {\nwhile (true) {\nList<AuthenticationExecutionModel> localExecutions = processor.getRealm().getAuthenticationExecutions(model.getParentFlow());\nAuthenticationExecutionModel parentFlowExecutionModel = processor.getRealm().getAuthenticationExecutionByFlowId(model.getParentFlow());\n- if (parentFlowExecutionModel != null &&\n- ((model.isRequired() && localExecutions.stream().allMatch(processor::isSuccessful)) ||\n- (model.isAlternative() && localExecutions.stream().anyMatch(processor::isSuccessful)))) {\n+\n+ if (parentFlowExecutionModel != null) {\n+ List<AuthenticationExecutionModel> requiredExecutions = new LinkedList<>();\n+ List<AuthenticationExecutionModel> alternativeExecutions = new LinkedList<>();\n+ fillListsOfExecutions(localExecutions, requiredExecutions, alternativeExecutions);\n+\n+ // Note: If we evaluate alternative execution, we will also doublecheck that there are not required elements in same subflow\n+ if ((model.isRequired() && requiredExecutions.stream().allMatch(processor::isSuccessful)) ||\n+ (model.isAlternative() && alternativeExecutions.stream().anyMatch(processor::isSuccessful) && requiredExecutions.isEmpty())) {\n+ logger.debugf(\"Flow '%s' successfully finished after children executions success\", logExecutionAlias(parentFlowExecutionModel));\nprocessor.getAuthenticationSession().setExecutionStatus(parentFlowExecutionModel.getId(), AuthenticationSessionModel.ExecutionStatus.SUCCESS);\n// Flow is successfully finished. Recursively check whether it's parent flow is now successful as well\n@@ -280,6 +218,9 @@ public class DefaultAuthenticationFlow implements AuthenticationFlow {\n} else {\nreturn model.getParentFlow();\n}\n+ } else {\n+ return model.getParentFlow();\n+ }\n}\n}\n@@ -428,21 +369,22 @@ public class DefaultAuthenticationFlow implements AuthenticationFlow {\nprivate Response processSingleFlowExecutionModel(AuthenticationExecutionModel model, boolean calledFromFlow) {\n- logger.debugv(\"check execution: {0} requirement: {1}\", model.getAuthenticator(), model.getRequirement());\n+ logger.debugf(\"check execution: '%s', requirement: '%s'\", logExecutionAlias(model), model.getRequirement());\nif (isProcessed(model)) {\n- logger.debug(\"execution is processed\");\n+ logger.debugf(\"execution '%s' is processed\", logExecutionAlias(model));\nreturn null;\n}\n//handle case where execution is a flow\nif (model.isAuthenticatorFlow()) {\n- logger.debug(\"execution is flow\");\nAuthenticationFlow authenticationFlow = processor.createFlowExecution(model.getFlowId(), model);\nResponse flowChallenge = authenticationFlow.processFlow();\nif (flowChallenge == null) {\nif (authenticationFlow.isSuccessful()) {\n+ logger.debugf(\"Flow '%s' successfully finished\", logExecutionAlias(model));\nprocessor.getAuthenticationSession().setExecutionStatus(model.getId(), AuthenticationSessionModel.ExecutionStatus.SUCCESS);\n} else {\n+ logger.debugf(\"Flow '%s' failed\", logExecutionAlias(model));\nprocessor.getAuthenticationSession().setExecutionStatus(model.getId(), AuthenticationSessionModel.ExecutionStatus.FAILED);\n}\nreturn null;\n@@ -498,6 +440,22 @@ public class DefaultAuthenticationFlow implements AuthenticationFlow {\nreturn processResult(context, false);\n}\n+ // Used for debugging purpose only. Log alias of authenticator (for non-flow executions) or alias of authenticationFlow (for flow executions)\n+ private String logExecutionAlias(AuthenticationExecutionModel executionModel) {\n+ if (executionModel.isAuthenticatorFlow()) {\n+ // Resolve authenticationFlow model in case of debug logging. Otherwise don't lookup flowModel just because of logging and return only flowId\n+ if (logger.isDebugEnabled()) {\n+ AuthenticationFlowModel flowModel = processor.getRealm().getAuthenticationFlowById(executionModel.getFlowId());\n+ if (flowModel != null) {\n+ return flowModel.getAlias() + \" flow\";\n+ }\n+ }\n+ return executionModel.getFlowId() + \" flow\";\n+ } else {\n+ return executionModel.getAuthenticator();\n+ }\n+ }\n+\n/**\n* This method creates the list of authenticators that is presented to the user. For a required execution, this is\n* only the credentials associated to the authenticator, and for an alternative execution, this is all other alternative\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserFlowTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserFlowTest.java", "diff": "@@ -45,6 +45,7 @@ import org.keycloak.testsuite.util.OAuthClient;\nimport org.keycloak.testsuite.authentication.ConditionalUserAttributeValueFactory;\nimport org.keycloak.testsuite.authentication.SetUserAttributeAuthenticatorFactory;\nimport org.keycloak.testsuite.util.URLUtils;\n+import org.keycloak.testsuite.util.WaitUtils;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\n@@ -63,6 +64,10 @@ import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.GOOGLE;\npublic class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\nprivate static final String INVALID_AUTH_CODE = \"Invalid authenticator code.\";\n+ private static final String USER_WITH_ONE_OTP_OTP_SECRET = \"DJmQfC73VGFhw7D4QJ8A\";\n+ private static final String USER_WITH_TWO_OTPS_OTP1_SECRET = \"DJmQfC73VGFhw7D4QJ8A\";\n+ private static final String USER_WITH_TWO_OTPS_OTP2_SECRET = \"ABCQfC73VGFhw7D4QJ8A\";\n+\n@ArquillianResource\nprotected OAuthClient oauth;\n@@ -160,16 +165,13 @@ public class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\nloginTotpPage.assertCurrent();\nloginTotpPage.assertOtpCredentialSelectorAvailability(false);\n- oneTimeCodePage.sendCode(getOtpCode(\"DJmQfC73VGFhw7D4QJ8A\"));\n+ oneTimeCodePage.sendCode(getOtpCode(USER_WITH_ONE_OTP_OTP_SECRET));\nAssert.assertFalse(loginPage.isCurrent());\nAssert.assertFalse(oneTimeCodePage.isOtpLabelPresent());\n}\n@Test\npublic void testUserWithTwoAdditionalFactors() {\n- final String firstKey = \"DJmQfC73VGFhw7D4QJ8A\";\n- final String secondKey = \"ABCQfC73VGFhw7D4QJ8A\";\n-\n// Provide username and password\nprovideUsernamePassword(\"user-with-two-configured-otp\");\nAssert.assertTrue(oneTimeCodePage.isOtpLabelPresent());\n@@ -181,17 +183,17 @@ public class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\n// Select \"second\" factor (which is unnamed as it doesn't have userLabel) but try to connect with the OTP code from the \"first\" one\nloginTotpPage.selectOtpCredential(OTPFormAuthenticator.UNNAMED);\n- loginTotpPage.login(getOtpCode(firstKey));\n+ loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP1_SECRET));\nAssert.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getError());\n// Select \"first\" factor but try to connect with the OTP code from the \"second\" one\nloginTotpPage.selectOtpCredential(\"first\");\n- loginTotpPage.login(getOtpCode(secondKey));\n+ loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP2_SECRET));\nAssert.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getError());\n// Select \"second\" factor and try to connect with its OTP code\nloginTotpPage.selectOtpCredential(OTPFormAuthenticator.UNNAMED);\n- loginTotpPage.login(getOtpCode(secondKey));\n+ loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP2_SECRET));\nAssert.assertFalse(oneTimeCodePage.isOtpLabelPresent());\n}\n@@ -617,7 +619,7 @@ public class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\nloginTotpPage.assertCurrent();\nloginTotpPage.assertOtpCredentialSelectorAvailability(false);\n- loginTotpPage.login(getOtpCode(\"DJmQfC73VGFhw7D4QJ8A\"));\n+ loginTotpPage.login(getOtpCode(USER_WITH_ONE_OTP_OTP_SECRET));\nAssert.assertFalse(loginTotpPage.isCurrent());\nevents.expectLogin().user(testRealm().users().search(\"user-with-one-configured-otp\").get(0).getId())\n.detail(Details.USERNAME, \"user-with-one-configured-otp\").assertEvent();\n@@ -683,7 +685,7 @@ public class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\nloginTotpPage.assertCurrent();\nloginTotpPage.assertOtpCredentialSelectorAvailability(true);\n- loginTotpPage.login(getOtpCode(\"DJmQfC73VGFhw7D4QJ8A\"));\n+ loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP1_SECRET));\nAssert.assertFalse(loginTotpPage.isCurrent());\nevents.expectLogin().user(userId).detail(Details.USERNAME, \"user-with-two-configured-otp\").assertEvent();\n} finally {\n@@ -1100,6 +1102,40 @@ public class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\n}\n}\n+ /**\n+ * Test for KEYCLOAK-12858\n+ *\n+ * Flow is configured, so that once user provides username, there are 2 alternatives:\n+ * - OTP\n+ * - Subflow1, which contains another conditional subflow2, which requires user to authenticate with Password if he has password configured\n+ *\n+ * After login with password and fulfill the conditional subflow2, the subflow1 should be considered successful as well and the OTP authentication should not be needed\n+ */\n+ @Test\n+ @AuthServerContainerExclude(REMOTE)\n+ public void testLoginWithAlternativeOTPAndConditionalPassword(){\n+ String newFlowAlias = \"browser - copy 2\";\n+ configureBrowserFlowWithAlternativeOTPAndConditionalPassword(newFlowAlias);\n+ try {\n+\n+ loginUsernameOnlyPage.open();\n+ loginUsernameOnlyPage.assertCurrent();\n+ loginUsernameOnlyPage.login(\"user-with-one-configured-otp\");\n+\n+ // Assert that the login skipped the OTP authenticator and moved to the password\n+ passwordPage.assertCurrent();\n+ passwordPage.assertTryAnotherWayLinkAvailability(true);\n+ passwordPage.login(\"password\");\n+\n+ Assert.assertFalse(loginPage.isCurrent());\n+ Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent());\n+ events.expectLogin().user(testRealm().users().search(\"user-with-one-configured-otp\").get(0).getId())\n+ .detail(Details.USERNAME, \"user-with-one-configured-otp\").assertEvent();\n+ } finally {\n+ revertFlows(newFlowAlias);\n+ }\n+ }\n+\n/**\n* This flow contains:\n* UsernameForm REQUIRED\n@@ -1110,7 +1146,7 @@ public class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\n*\n* The password form is in a sub-subflow, because otherwise credential preference mechanisms would take over and any\n* way go into the password form. Note that this flow only works for the test because WebAuthn is a isUserSetupAllowed\n- * flow that is not a CredentialValidator. When this changes, this flow will have to be modified to use another appropriate\n+ * flow . When this changes, this flow will have to be modified to use another appropriate\n* authenticator.\n*\n* @param newFlowAlias\n@@ -1131,6 +1167,38 @@ public class BrowserFlowTest extends AbstractTestRealmKeycloakTest {\n);\n}\n+ /**\n+ * This flow contains:\n+ * UsernameForm REQUIRED\n+ * Subflow REQUIRED\n+ * ** OTP ALTERNATIVE\n+ * ** password-subflow ALTERNATIVE\n+ * **** PasswordConditional subflow CONDITIONAL\n+ * ****** ConditionalUserConfiguredOTP REQUIRED\n+ * ****** Password REQUIRED\n+ *\n+ * @param newFlowAlias\n+ */\n+ private void configureBrowserFlowWithAlternativeOTPAndConditionalPassword(String newFlowAlias) {\n+ testingClient.server(\"test\").run(session -> FlowUtil.inCurrentRealm(session).copyBrowserFlow(newFlowAlias));\n+ testingClient.server(\"test\").run(session -> FlowUtil.inCurrentRealm(session)\n+ .selectFlow(newFlowAlias)\n+ .inForms(forms -> forms\n+ .clear()\n+ .addAuthenticatorExecution(Requirement.REQUIRED, UsernameFormFactory.PROVIDER_ID)\n+ .addSubFlowExecution(Requirement.REQUIRED, subflow -> subflow\n+ .addAuthenticatorExecution(Requirement.ALTERNATIVE, OTPFormAuthenticatorFactory.PROVIDER_ID)\n+ .addSubFlowExecution(Requirement.ALTERNATIVE, sf -> sf\n+ .addSubFlowExecution(Requirement.CONDITIONAL, sf2 -> sf2\n+ .addAuthenticatorExecution(Requirement.REQUIRED, ConditionalUserConfiguredAuthenticatorFactory.PROVIDER_ID)\n+ .addAuthenticatorExecution(Requirement.REQUIRED, PasswordFormFactory.PROVIDER_ID)\n+ )\n+ )\n+ )\n+ ).defineAsBrowserFlow() // Activate this new flow\n+ );\n+ }\n+\nprivate void revertFlows(String flowToDeleteAlias) {\nrevertFlows(testRealm(), flowToDeleteAlias);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12858 Authenticator is sometimes required even when configured as alternative
339,179
12.02.2020 15:41:06
-3,600
167f73f54e733beeeb052ee74f0d8fe8808f530a
Don't use GenericFilter in server-authz test application
[ { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/test-apps/servlet-authz/src/main/java/org/keycloak/testsuite/servletauthz/TestFilter.java", "new_path": "testsuite/integration-arquillian/test-apps/servlet-authz/src/main/java/org/keycloak/testsuite/servletauthz/TestFilter.java", "diff": "package org.keycloak.testsuite.servletauthz;\n+import javax.servlet.Filter;\nimport javax.servlet.FilterChain;\n-import javax.servlet.GenericFilter;\n+import javax.servlet.FilterConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\n@@ -32,10 +33,16 @@ import org.keycloak.util.JsonSerialization;\n/**\n* @author <a href=\"mailto:[email protected]\">Pedro Igor</a>\n*/\n-public class TestFilter extends GenericFilter {\n+public class TestFilter implements Filter {\n+\n+ @Override\n+ public void init(FilterConfig filterConfig) throws ServletException {\n+\n+ }\n+\n@Override\npublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)\n- throws IOException, ServletException {\n+ throws IOException {\nHttpServletRequest req = (HttpServletRequest) request;\nif (req.getRequestURI().endsWith(\"/body\")) {\n@@ -46,4 +53,10 @@ public class TestFilter extends GenericFilter {\nwriter.flush();\n}\n}\n+\n+ @Override\n+ public void destroy() {\n+\n+ }\n+\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12969 Don't use GenericFilter in server-authz test application
339,235
14.02.2020 11:37:16
-3,600
536824beb65bc36d7218870f6550d155fec11b18
Use Long for time based values in JsonWebToken
[ { "change_type": "MODIFY", "old_path": "core/src/main/java/org/keycloak/representations/IDToken.java", "new_path": "core/src/main/java/org/keycloak/representations/IDToken.java", "diff": "package org.keycloak.representations;\n+import com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport org.keycloak.TokenCategory;\n@@ -61,8 +62,7 @@ public class IDToken extends JsonWebToken {\n@JsonProperty(NONCE)\nprotected String nonce;\n- @JsonProperty(AUTH_TIME)\n- protected int authTime;\n+ protected Long auth_time;\n@JsonProperty(SESSION_STATE)\nprotected String sessionState;\n@@ -149,12 +149,28 @@ public class IDToken extends JsonWebToken {\nthis.nonce = nonce;\n}\n+ public Long getAuth_time() {\n+ return auth_time;\n+ }\n+\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #getAuth_time()} instead.\n+ */\n+ @Deprecated\n+ @JsonIgnore\npublic int getAuthTime() {\n- return authTime;\n+ return auth_time != null ? auth_time.intValue() : 0;\n}\n+ public void setAuth_time(Long auth_time) {\n+ this.auth_time = auth_time;\n+ }\n+\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #setAuth_time(Long)} ()} instead.\n+ */\npublic void setAuthTime(int authTime) {\n- this.authTime = authTime;\n+ this.auth_time = Long.valueOf(authTime);\n}\npublic String getSessionState() {\n" }, { "change_type": "MODIFY", "old_path": "core/src/main/java/org/keycloak/representations/JsonWebToken.java", "new_path": "core/src/main/java/org/keycloak/representations/JsonWebToken.java", "diff": "@@ -41,12 +41,11 @@ import java.util.Map;\npublic class JsonWebToken implements Serializable, Token {\n@JsonProperty(\"jti\")\nprotected String id;\n- @JsonProperty(\"exp\")\n- protected int expiration;\n- @JsonProperty(\"nbf\")\n- protected int notBefore;\n- @JsonProperty(\"iat\")\n- protected int issuedAt;\n+\n+ protected Long exp;\n+ protected Long nbf;\n+ protected Long iat;\n+\n@JsonProperty(\"iss\")\nprotected String issuer;\n@JsonProperty(\"aud\")\n@@ -70,33 +69,68 @@ public class JsonWebToken implements Serializable, Token {\nreturn this;\n}\n+ public Long getExp() {\n+ return exp;\n+ }\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #getExp()} instead.\n+ */\n+ @Deprecated\n+ @JsonIgnore\npublic int getExpiration() {\n- return expiration;\n+ return exp != null ? exp.intValue() : 0;\n+ }\n+\n+ public JsonWebToken exp(Long exp) {\n+ this.exp = exp;\n+ return this;\n}\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #exp(Long)} instead.\n+ */\npublic JsonWebToken expiration(int expiration) {\n- this.expiration = expiration;\n+ this.exp = Long.valueOf(expiration);\nreturn this;\n}\n@JsonIgnore\npublic boolean isExpired() {\n- return Time.currentTime() > expiration;\n+ return exp != null && exp != 0 ? Time.currentTime() > exp : false;\n+ }\n+\n+ public Long getNbf() {\n+ return nbf;\n}\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #getNbf()} instead.\n+ */\n+ @Deprecated\n+ @JsonIgnore\npublic int getNotBefore() {\n- return notBefore;\n+ return nbf != null ? nbf.intValue() : 0;\n}\n+ public JsonWebToken nbf(Long nbf) {\n+ this.nbf = nbf;\n+ return this;\n+ }\n+\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #nbf(Long)} instead.\n+ */\n+ @Deprecated\n+ @JsonIgnore\npublic JsonWebToken notBefore(int notBefore) {\n- this.notBefore = notBefore;\n+ this.nbf = Long.valueOf(notBefore);\nreturn this;\n}\n@JsonIgnore\npublic boolean isNotBefore(int allowedTimeSkew) {\n- return Time.currentTime() + allowedTimeSkew >= notBefore;\n+ return nbf != null ? Time.currentTime() + allowedTimeSkew >= nbf : true;\n}\n/**\n@@ -111,11 +145,20 @@ public class JsonWebToken implements Serializable, Token {\n@JsonIgnore\npublic boolean isActive(int allowedTimeSkew) {\n- return (!isExpired() || expiration == 0) && (isNotBefore(allowedTimeSkew) || notBefore == 0);\n+ return !isExpired() && isNotBefore(allowedTimeSkew);\n+ }\n+\n+ public Long getIat() {\n+ return iat;\n}\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #getIat()} instead.\n+ */\n+ @Deprecated\n+ @JsonIgnore\npublic int getIssuedAt() {\n- return issuedAt;\n+ return iat != null ? iat.intValue() : 0;\n}\n/**\n@@ -123,12 +166,22 @@ public class JsonWebToken implements Serializable, Token {\n*/\n@JsonIgnore\npublic JsonWebToken issuedNow() {\n- issuedAt = Time.currentTime();\n+ iat = Long.valueOf(Time.currentTime());\n+ return this;\n+ }\n+\n+ public JsonWebToken iat(Long iat) {\n+ this.iat = iat;\nreturn this;\n}\n+ /**\n+ * @deprecated int will overflow with values after 2038. Use {@link #iat(Long)} ()} instead.\n+ */\n+ @Deprecated\n+ @JsonIgnore\npublic JsonWebToken issuedAt(int issuedAt) {\n- this.issuedAt = issuedAt;\n+ this.iat = Long.valueOf(issuedAt);\nreturn this;\n}\n" }, { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/authentication/actiontoken/DefaultActionTokenKey.java", "new_path": "services/src/main/java/org/keycloak/authentication/actiontoken/DefaultActionTokenKey.java", "diff": "@@ -46,7 +46,7 @@ public class DefaultActionTokenKey extends JsonWebToken implements ActionTokenKe\npublic DefaultActionTokenKey(String userId, String actionId, int absoluteExpirationInSecs, UUID actionVerificationNonce) {\nthis.subject = userId;\nthis.type = actionId;\n- this.expiration = absoluteExpirationInSecs;\n+ this.exp = Long.valueOf(absoluteExpirationInSecs);\nthis.actionVerificationNonce = actionVerificationNonce == null ? UUID.randomUUID() : actionVerificationNonce;\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java", "diff": "@@ -222,6 +222,15 @@ public class AccessTokenTest extends AbstractKeycloakTest {\nassertEquals(sessionId, token.getSessionState());\n+ assertNull(token.getNbf());\n+ assertEquals(0, token.getNotBefore());\n+\n+ assertNotNull(token.getIat());\n+ assertEquals(token.getIat().intValue(), token.getIssuedAt());\n+\n+ assertNotNull(token.getExp());\n+ assertEquals(token.getExp().intValue(), token.getExpiration());\n+\nassertEquals(1, token.getRealmAccess().getRoles().size());\nassertTrue(token.getRealmAccess().isUserInRole(\"user\"));\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenIntrospectionTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenIntrospectionTest.java", "diff": "@@ -108,7 +108,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {\nassertEquals(\"test-app\", jsonNode.get(\"client_id\").asText());\nassertTrue(jsonNode.has(\"exp\"));\nassertTrue(jsonNode.has(\"iat\"));\n- assertTrue(jsonNode.has(\"nbf\"));\n+ assertFalse(jsonNode.has(\"nbf\"));\nassertTrue(jsonNode.has(\"sub\"));\nassertTrue(jsonNode.has(\"aud\"));\nassertTrue(jsonNode.has(\"iss\"));\n@@ -121,7 +121,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {\nassertEquals(\"test-app\", rep.getClientId());\nassertEquals(jsonNode.get(\"exp\").asInt(), rep.getExpiration());\nassertEquals(jsonNode.get(\"iat\").asInt(), rep.getIssuedAt());\n- assertEquals(jsonNode.get(\"nbf\").asInt(), rep.getNotBefore());\n+ assertEquals(jsonNode.get(\"nbf\"), rep.getNbf());\nassertEquals(jsonNode.get(\"sub\").asText(), rep.getSubject());\nList<String> audiences = new ArrayList<>();\n@@ -163,7 +163,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {\nassertEquals(\"test-app\", jsonNode.get(\"client_id\").asText());\nassertTrue(jsonNode.has(\"exp\"));\nassertTrue(jsonNode.has(\"iat\"));\n- assertTrue(jsonNode.has(\"nbf\"));\n+ assertFalse(jsonNode.has(\"nbf\"));\nassertTrue(jsonNode.has(\"sub\"));\nassertTrue(jsonNode.has(\"aud\"));\nassertTrue(jsonNode.has(\"iss\"));\n@@ -177,7 +177,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {\nassertEquals(jsonNode.get(\"session_state\").asText(), rep.getSessionState());\nassertEquals(jsonNode.get(\"exp\").asInt(), rep.getExpiration());\nassertEquals(jsonNode.get(\"iat\").asInt(), rep.getIssuedAt());\n- assertEquals(jsonNode.get(\"nbf\").asInt(), rep.getNotBefore());\n+ assertEquals(jsonNode.get(\"nbf\"), rep.getNbf());\nassertEquals(jsonNode.get(\"iss\").asText(), rep.getIssuer());\nassertEquals(jsonNode.get(\"jti\").asText(), rep.getId());\nassertEquals(jsonNode.get(\"typ\").asText(), \"Refresh\");\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12960 Use Long for time based values in JsonWebToken
339,235
18.02.2020 20:19:15
-3,600
04903666d1921a185f7f316723390903dc63a16b
Fix admin console with base theme
[ { "change_type": "ADD", "old_path": null, "new_path": "themes/src/main/resources/theme/base/admin/theme.properties", "diff": "+import=common/keycloak\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "themes/src/main/resources/theme/keycloak/admin/theme.properties", "new_path": "themes/src/main/resources/theme/keycloak/admin/theme.properties", "diff": "parent=base\n-import=common/keycloak\nstyles=node_modules/patternfly/dist/css/patternfly.min.css node_modules/patternfly/dist/css/patternfly-additions.min.css node_modules/select2/select2.css css/styles.css lib/angular/treeview/css/angular.treeview.css node_modules/text-security/dist/text-security.css\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12597 Fix admin console with base theme
339,235
18.02.2020 20:29:31
-3,600
06576a44c965e85214b4dbdbd6e488d2d1eb8feb
Add no cache headers to account form service
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/forms/account/freemarker/FreeMarkerAccountProvider.java", "new_path": "services/src/main/java/org/keycloak/forms/account/freemarker/FreeMarkerAccountProvider.java", "diff": "@@ -37,6 +37,7 @@ import org.keycloak.models.RealmModel;\nimport org.keycloak.models.UserModel;\nimport org.keycloak.models.UserSessionModel;\nimport org.keycloak.models.utils.FormMessage;\n+import org.keycloak.services.util.CacheControlUtil;\nimport org.keycloak.theme.BrowserSecurityHeaderSetup;\nimport org.keycloak.theme.FreeMarkerException;\nimport org.keycloak.theme.FreeMarkerUtil;\n@@ -49,6 +50,7 @@ import org.keycloak.theme.beans.MessageType;\nimport org.keycloak.theme.beans.MessagesPerFieldBean;\nimport org.keycloak.utils.MediaType;\n+import javax.ws.rs.core.CacheControl;\nimport javax.ws.rs.core.HttpHeaders;\nimport javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.core.Response;\n@@ -270,6 +272,7 @@ public class FreeMarkerAccountProvider implements AccountProvider {\nString result = freeMarker.processTemplate(attributes, Templates.getTemplate(page), theme);\nResponse.ResponseBuilder builder = Response.status(status).type(MediaType.TEXT_HTML_UTF_8_TYPE).language(locale).entity(result);\nBrowserSecurityHeaderSetup.headers(builder, realm);\n+ builder.cacheControl(CacheControlUtil.noCache());\nreturn builder.build();\n} catch (FreeMarkerException e) {\nlogger.error(\"Failed to process template\", e);\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-13032 Add no cache headers to account form service
339,235
18.02.2020 21:06:40
-3,600
9a3a358b964e76b476bb1a1c4b94623fb574adc8
Lower-case passwords before checking with password blacklist
[ { "change_type": "MODIFY", "old_path": "server-spi-private/src/main/java/org/keycloak/policy/BlacklistPasswordPolicyProvider.java", "new_path": "server-spi-private/src/main/java/org/keycloak/policy/BlacklistPasswordPolicyProvider.java", "diff": "@@ -45,7 +45,7 @@ public class BlacklistPasswordPolicyProvider implements PasswordPolicyProvider {\nPasswordBlacklist blacklist = (FileBasedPasswordBlacklist) policyConfig;\n- if (!blacklist.contains(password)) {\n+ if (!blacklist.contains(password.toLowerCase())) {\nreturn null;\n}\n" }, { "change_type": "MODIFY", "old_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordPolicyTest.java", "new_path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordPolicyTest.java", "diff": "@@ -154,6 +154,7 @@ public class PasswordPolicyTest extends AbstractKeycloakTest {\nAssert.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate(\"jdoe\", \"blacklisted1\").getMessage());\nAssert.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate(\"jdoe\", \"blacklisted2\").getMessage());\n+ Assert.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate(\"jdoe\", \"bLaCkLiSteD2\").getMessage());\nassertNull(policyManager.validate(\"jdoe\", \"notblacklisted\"));\n});\n}\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-11700 Lower-case passwords before checking with password blacklist
339,235
18.02.2020 20:50:28
-3,600
d8d81ee1626563b86e9ff1dea3e7a438457c2e11
Show page not found for /account/log if events are disabled for the realm
[ { "change_type": "MODIFY", "old_path": "services/src/main/java/org/keycloak/services/resources/account/AccountFormService.java", "new_path": "services/src/main/java/org/keycloak/services/resources/account/AccountFormService.java", "diff": "@@ -80,6 +80,7 @@ import org.keycloak.util.JsonSerialization;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.FormParam;\nimport javax.ws.rs.GET;\n+import javax.ws.rs.NotFoundException;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\n@@ -287,6 +288,10 @@ public class AccountFormService extends AbstractSecuredLocalService {\n@Path(\"log\")\n@GET\npublic Response logPage() {\n+ if (!realm.isEventsEnabled()) {\n+ throw new NotFoundException();\n+ }\n+\nif (auth != null) {\nList<Event> events = eventStore.createQuery().type(Constants.EXPOSED_LOG_EVENTS).user(auth.getUser().getId()).maxResults(30).getResultList();\nfor (Event e : events) {\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": "@@ -1006,15 +1006,23 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {\nAssert.assertEquals(\"No access\", errorPage.getError());\n}\n- private void setEventsEnabled() {\n+ private void setEventsEnabled(boolean eventsEnabled) {\nRealmRepresentation testRealm = testRealm().toRepresentation();\n- testRealm.setEventsEnabled(true);\n+ testRealm.setEventsEnabled(eventsEnabled);\ntestRealm().update(testRealm);\n}\n+\n+ @Test\n+ public void viewLogNotEnabled() {\n+ logPage.open();\n+ assertTrue(errorPage.isCurrent());\n+ assertEquals(\"Page not found\", errorPage.getError());\n+ }\n+\n@Test\npublic void viewLog() {\n- setEventsEnabled();\n+ setEventsEnabled(true);\nList<EventRepresentation> expectedEvents = new LinkedList<>();\n@@ -1053,6 +1061,8 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {\nAssert.fail(\"Event not found \" + e.getType());\n}\n}\n+\n+ setEventsEnabled(false);\n}\n@Test\n" } ]
Java
Apache License 2.0
keycloak/keycloak
KEYCLOAK-12268 Show page not found for /account/log if events are disabled for the realm