From fc9a0e1766838c1cf5274fd6710c99aba9a74ee2 Mon Sep 17 00:00:00 2001 From: Steeve Beroard Date: Fri, 17 May 2019 18:14:16 +0200 Subject: [PATCH] [KEYCLOAK-8104] Keycloak SAML Adapter does not support clockSkew configuration Co-Authored-By: vramik --- .../adapters/saml/DefaultSamlDeployment.java | 11 + .../adapters/saml/SamlDeployment.java | 6 + .../keycloak/adapters/saml/config/IDP.java | 20 + .../config/parsers/DeploymentBuilder.java | 19 +- .../saml/config/parsers/IdpParser.java | 8 + .../parsers/KeycloakSamlAdapterV1QNames.java | 2 + .../AbstractSamlAuthenticationHandler.java | 1 + .../schema/keycloak_saml_adapter_1_11.xsd | 492 ++++++++++++++++++ .../KeycloakSamlAdapterXMLParserTest.java | 31 +- ...l-with-allowed-clock-skew-default-unit.xml | 78 +++ ...saml-with-allowed-clock-skew-with-unit.xml | 78 +++ .../core/saml/v2/util/XMLTimeUtil.java | 26 +- .../common/cli/add-adapter-log-level.cli | 2 + .../adapter/servlet/SendUsernameServlet.java | 4 +- .../page/SalesPostClockSkewServlet.java | 36 ++ .../AdapterTestExecutionDecider.java | 6 +- .../arquillian/AppServerTestEnricher.java | 35 +- .../arquillian/DeploymentTargetModifier.java | 5 +- .../testsuite/arquillian/TestContext.java | 9 +- .../adapter/AbstractServletsAdapterTest.java | 25 +- .../servlet/SAMLClockSkewAdapterTest.java | 167 ++++++ .../WEB-INF/keycloak-saml.xml | 45 ++ .../sales-post-clock-skew/WEB-INF/web.xml | 72 +++ .../adapter-test/keycloak-saml/testsaml.json | 14 + .../undertow/UndertowDeployerHelper.java | 17 +- 25 files changed, 1159 insertions(+), 50 deletions(-) create mode 100644 adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_11.xsd create mode 100644 adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-default-unit.xml create mode 100644 adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-with-unit.xml create mode 100644 testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostClockSkewServlet.java create mode 100644 testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLClockSkewAdapterTest.java create mode 100644 testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/keycloak-saml.xml create mode 100644 testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/web.xml diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java index 2b2ba061f6..93097749a9 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java @@ -205,6 +205,7 @@ public class DefaultSamlDeployment implements SamlDeployment { private SingleLogoutService singleLogoutService; private final List signatureValidationKeys = new LinkedList<>(); private int minTimeBetweenDescriptorRequests; + private int allowedClockSkew; private HttpClient client; private String metadataUrl; @@ -284,6 +285,16 @@ public class DefaultSamlDeployment implements SamlDeployment { public void setMetadataUrl(String metadataUrl) { this.metadataUrl = metadataUrl; } + + @Override + public int getAllowedClockSkew() { + return allowedClockSkew; + } + + + public void setAllowedClockSkew(int allowedClockSkew) { + this.allowedClockSkew = allowedClockSkew; + } } private IDP idp; diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java index 0b7ac40ecf..f59c42d6ae 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java @@ -85,6 +85,12 @@ public interface SamlDeployment { */ HttpClient getClient(); + /** + * Returns allowed time difference (in milliseconds) between IdP and SP + * @return see description + */ + int getAllowedClockSkew(); + public interface SingleSignOnService { /** * Returns {@code true} if the requests to IdP need to be signed by SP key. diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/IDP.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/IDP.java index 25097aa215..2ffde0b882 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/IDP.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/IDP.java @@ -19,6 +19,8 @@ package org.keycloak.adapters.saml.config; import java.io.Serializable; import java.util.List; +import java.util.concurrent.TimeUnit; + import org.keycloak.adapters.cloned.AdapterHttpClientConfig; /** @@ -270,6 +272,8 @@ public class IDP implements Serializable { private AdapterHttpClientConfig httpClientConfig = new HttpClientConfig(); private boolean signaturesRequired = false; private String metadataUrl; + private Integer allowedClockSkew; + private TimeUnit allowedClockSkewUnit; public String getEntityID() { return entityID; @@ -348,4 +352,20 @@ public class IDP implements Serializable { public void setMetadataUrl(String metadataUrl) { this.metadataUrl = metadataUrl; } + + public Integer getAllowedClockSkew() { + return allowedClockSkew; + } + + public void setAllowedClockSkew(Integer allowedClockSkew) { + this.allowedClockSkew = allowedClockSkew; + } + + public TimeUnit getAllowedClockSkewUnit() { + return allowedClockSkewUnit; + } + + public void setAllowedClockSkewUnit(TimeUnit allowedClockSkewUnit) { + this.allowedClockSkewUnit = allowedClockSkewUnit; + } } diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java index e33f4e768b..f02d88e6c6 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java @@ -44,10 +44,8 @@ import java.util.Set; import org.keycloak.adapters.cloned.HttpClientBuilder; import java.net.URI; import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; -import java.util.logging.Level; +import java.util.concurrent.TimeUnit; /** * @author Bill Burke @@ -172,6 +170,9 @@ public class DeploymentBuilder { sso.setResponseBinding(SamlDeployment.Binding.parseBinding( idp.getSingleSignOnService().getResponseBinding())); } + if (idp.getAllowedClockSkew() != null) { + defaultIDP.setAllowedClockSkew(convertClockSkewInMillis(idp.getAllowedClockSkew(), idp.getAllowedClockSkewUnit())); + } if (idp.getSingleSignOnService().getAssertionConsumerServiceUrl() != null) { if (! idp.getSingleSignOnService().getAssertionConsumerServiceUrl().endsWith("/saml")) { throw new RuntimeException("AssertionConsumerServiceUrl must end with \"/saml\"."); @@ -214,6 +215,18 @@ public class DeploymentBuilder { return deployment; } + private int convertClockSkewInMillis(int duration, TimeUnit unit) { + int durationMillis = (int) unit.toMillis(duration); + switch (unit) { + case NANOSECONDS: + case MICROSECONDS: + log.warn("Clock skew value will be rounded down."); + default: + log.info("Clock skew set to " + durationMillis + "ms."); + } + return durationMillis; + } + private void processSigningKey(DefaultSamlDeployment.DefaultIDP idp, Key key, ResourceLoader resourceLoader) throws RuntimeException { PublicKey publicKey; if (key.getKeystore() != null) { diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/IdpParser.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/IdpParser.java index d759059b8a..ae051180b3 100644 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/IdpParser.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/IdpParser.java @@ -23,6 +23,7 @@ import org.keycloak.saml.common.util.StaxParserUtil; import javax.xml.stream.XMLEventReader; import javax.xml.stream.events.StartElement; +import java.util.concurrent.TimeUnit; /** * @author Bill Burke @@ -72,6 +73,13 @@ public class IdpParser extends AbstractKeycloakSamlAdapterV1Parser { case SINGLE_LOGOUT_SERVICE: target.setSingleLogoutService(SingleLogoutServiceParser.getInstance().parse(xmlEventReader)); break; + + case ALLOWED_CLOCK_SKEW: + String timeUnitString = StaxParserUtil.getAttributeValueRP(elementDetail, KeycloakSamlAdapterV1QNames.ATTR_UNIT); + target.setAllowedClockSkewUnit(timeUnitString == null ? TimeUnit.SECONDS : TimeUnit.valueOf(timeUnitString)); + StaxParserUtil.advance(xmlEventReader); + target.setAllowedClockSkew(Integer.parseInt(StaxParserUtil.getElementText(xmlEventReader))); + break; } } } diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterV1QNames.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterV1QNames.java index 1034417425..e0f8288b7d 100644 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterV1QNames.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterV1QNames.java @@ -25,6 +25,7 @@ import javax.xml.namespace.QName; */ public enum KeycloakSamlAdapterV1QNames implements HasQName { + ALLOWED_CLOCK_SKEW("AllowedClockSkew"), ATTRIBUTE("Attribute"), CERTIFICATE("Certificate"), CERTIFICATE_PEM("CertificatePem"), @@ -81,6 +82,7 @@ public enum KeycloakSamlAdapterV1QNames implements HasQName { ATTR_TRUSTSTORE_PASSWORD(null, "truststorePassword"), ATTR_TURN_OFF_CHANGE_SESSSION_ID_ON_LOGIN(null, "turnOffChangeSessionIdOnLogin"), ATTR_TYPE(null, "type"), + ATTR_UNIT(null, "unit"), ATTR_VALIDATE_ASSERTION_SIGNATURE(null, "validateAssertionSignature"), ATTR_VALIDATE_REQUEST_SIGNATURE(null, "validateRequestSignature"), ATTR_VALIDATE_RESPONSE_SIGNATURE(null, "validateResponseSignature"), diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java index 9a159df864..cb0ac60fdb 100644 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java @@ -345,6 +345,7 @@ public abstract class AbstractSamlAuthenticationHandler implements SamlAuthentic assertion = AssertionUtil.getAssertion(responseHolder, responseType, deployment.getDecryptionKey()); ConditionsValidator.Builder cvb = new ConditionsValidator.Builder(assertion.getID(), assertion.getConditions(), destinationValidator); try { + cvb.clockSkewInMillis(deployment.getIDP().getAllowedClockSkew()); cvb.addAllowedAudience(URI.create(deployment.getEntityID())); // getDestination has been validated to match request URL already so it matches SAML endpoint cvb.addAllowedAudience(URI.create(responseType.getDestination())); diff --git a/adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_11.xsd b/adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_11.xsd new file mode 100644 index 0000000000..df961db25a --- /dev/null +++ b/adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_11.xsd @@ -0,0 +1,492 @@ + + + + + + + + + + Keycloak SAML Adapter configuration file. + + + + + Describes SAML service provider configuration. + + + + + + + + + + + List of service provider encryption and validation keys. + + If the IDP requires that the client application (SP) sign all of its requests and/or if the IDP will encrypt assertions, you must define the keys used to do this. For client signed documents you must define both the private and public key or certificate that will be used to sign documents. For encryption, you only have to define the private key that will be used to decrypt. + + + + + When creating a Java Principal object that you obtain from methods like HttpServletRequest.getUserPrincipal(), you can define what name that is returned by the Principal.getName() method. + + + + + Defines what SAML attributes within the assertion received from the user should be used as role identifiers within the Java EE Security Context for the user. + By default Role attribute values are converted to Java EE roles. Some IDPs send roles via a member or memberOf attribute assertion. You can define one or more Attribute elements to specify which SAML attributes must be converted into roles. + + + + + Describes configuration of SAML identity provider for this service provider. + + + + + + This is the identifier for this client. The IDP needs this value to determine who the client is that is communicating with it. + + + + + SSL policy the adapter will enforce. + + + + + SAML clients can request a specific NameID Subject format. Fill in this value if you want a specific format. It must be a standard SAML format identifier, i.e. urn:oasis:names:tc:SAML:2.0:nameid-format:transient. By default, no special format is requested. + + + + + URL of the logout page. + + + + + SAML clients can request that a user is re-authenticated even if they are already logged in at the IDP. Default value is false. + + + + + SAML clients can request that a user is never asked to authenticate even if they are not logged in at the IDP. Set this to true if you want this. Do not use together with forceAuthentication as they are opposite. Default value is false. + + + + + The session id is changed by default on a successful login on some platforms to plug a security attack vector. Change this to true to disable this. It is recommended you do not turn it off. Default value is false. + + + + + This should be set to true if your application serves both a web application and web services (e.g. SOAP or REST). It allows you to redirect unauthenticated users of the web application to the Keycloak login page, but send an HTTP 401 status code to unauthenticated SOAP or REST clients instead as they would not understand a redirect to the login page. Keycloak auto-detects SOAP or REST clients based on typical headers like X-Requested-With, SOAPAction or Accept. The default value is false. + + + + + + + + + Describes a single key used for signing or encryption. + + + + + + + + + Java keystore to load keys and certificates from. + + + + + Private key (PEM format) + + + + + Public key (PEM format) + + + + + Certificate key (PEM format) + + + + + + Flag defining whether the key should be used for signing. + + + + + Flag defining whether the key should be used for encryption + + + + + + + + Private key declaration + + + + + Certificate declaration + + + + + + File path to the key store. + + + + + WAR resource path to the key store. This is a path used in method call to ServletContext.getResourceAsStream(). + + + + + The password of the key store. + + + + + + + Alias that points to the key or cert within the keystore. + + + + + Keystores require an additional password to access private keys. In the PrivateKey element you must define this password within a password attribute. + + + + + + + Alias that points to the key or cert within the keystore. + + + + + + + Policy used to populate value of Java Principal object obtained from methods like HttpServletRequest.getUserPrincipal(). + + + + + Name of the SAML assertion attribute to use within. + + + + + + + + This policy just uses whatever the SAML subject value is. This is the default setting + + + + + This will pull the value from one of the attributes declared in the SAML assertion received from the server. You'll need to specify the name of the SAML assertion attribute to use within the attribute XML attribute. + + + + + + + + + All requests must come in via HTTPS. + + + + + Only non-private IP addresses must come over the wire via HTTPS. + + + + + no requests are required to come over via HTTPS. + + + + + + + + + + + + + + + + + + + + + + + Specifies SAML attribute to be converted into roles. + + + + + + + + Specifies name of the SAML attribute to be converted into roles. + + + + + + + + Configuration of the login SAML endpoint of the IDP. + + + + + Configuration of the logout SAML endpoint of the IDP + + + + + The Keys sub element of IDP is only used to define the certificate or public key to use to verify documents signed by the IDP. + + + + + Configuration of HTTP client used for automatic obtaining of certificates containing public keys for IDP signature verification via SAML descriptor of the IDP. + + + + + This defines the allowed clock skew between IDP and SP in milliseconds. The default value is 0. + + + + + + issuer ID of the IDP. + + + + + If set to true, the client adapter will sign every document it sends to the IDP. Also, the client will expect that the IDP will be signing any documents sent to it. This switch sets the default for all request and response types. + + + + + Signature algorithm that the IDP expects signed documents to use. Defaults to RSA_SHA256 + + + + + This is the signature canonicalization method that the IDP expects signed documents to use. The default value is https://www.w3.org/2001/10/xml-exc-c14n# and should be good for most IDPs. + + + + + + + + + + The URL used to retrieve the IDP metadata, currently this is only used to pick up signing and encryption keys periodically which allow cycling of these keys on the IDP without manual changes on the SP side. + + + + + + + Should the client sign authn requests? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect the IDP to sign the assertion response document sent back from an auhtn request? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect the IDP to sign the individual assertions sent back from an auhtn request? Defaults to whatever the IDP signaturesRequired element value is. + + + + + SAML binding type used for communicating with the IDP. The default value is POST, but you can set it to REDIRECT as well. + + + + + SAML allows the client to request what binding type it wants authn responses to use. This value maps to ProtocolBinding attribute in SAML AuthnRequest. The default is that the client will not request a specific binding type for responses. + + + + + This is the URL for the IDP login service that the client will send requests to. + + + + + URL of the assertion consumer service (ACS) where the IDP login service should send responses to. By default it is unset, relying on the IdP settings. When set, it must end in "/saml". This property is typically accompanied by the responseBinding attribute. + + + + + + + + Should the client sign authn requests? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client sign logout responses it sends to the IDP requests? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect signed logout request documents from the IDP? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect signed logout response documents from the IDP? Defaults to whatever the IDP signaturesRequired element value is. + + + + + This is the SAML binding type used for communicating SAML requests to the IDP. The default value is POST. + + + + + This is the SAML binding type used for communicating SAML responses to the IDP. The default value is POST. + + + + + This is the URL for the IDP's logout service when using the POST binding. This setting is REQUIRED if using the POST binding. + + + + + This is the URL for the IDP's logout service when using the REDIRECT binding. This setting is REQUIRED if using the REDIRECT binding. + + + + + + + + If the the IDP server requires HTTPS and this config option is set to true the IDP's certificate + is validated via the truststore, but host name validation is not done. This setting should only be used during + development and never in production as it will partly disable verification of SSL certificates. + This seting may be useful in test environments. The default value is false. + + + + + This is the file path to a keystore file. This keystore contains client certificate + for two-way SSL when the adapter makes HTTPS requests to the IDP server. + + + + + Password for the client keystore and for the client's key. + + + + + Defines number of pooled connections. + + + + + If the the IDP server requires HTTPS and this config option is set to true you do not have to specify a truststore. + This setting should only be used during development and never in production as it will disable verification of SSL certificates. + The default value is false. + + + + + URL to HTTP proxy to use for HTTP connections. + + + + + The value is the file path to a keystore file. If you prefix the path with classpath:, + then the truststore will be obtained from the deployment's classpath instead. Used for outgoing + HTTPS communications to the IDP server. Client making HTTPS requests need + a way to verify the host of the server they are talking to. This is what the trustore does. + The keystore contains one or more trusted host certificates or certificate authorities. + You can create this truststore by extracting the public certificate of the IDP's SSL keystore. + + + + + + Password for the truststore keystore. + + + + + + The value is the allowed clock skew between the IDP and the SP. + + + + + + + + + + Time unit for the value of the clock skew. + + + + + + + + + + diff --git a/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java b/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java index 6a1c174f4a..c2a1f1f7df 100755 --- a/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java +++ b/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java @@ -31,6 +31,8 @@ import org.junit.Rule; import org.junit.rules.ExpectedException; import org.keycloak.saml.common.exceptions.ParsingException; import java.io.IOException; +import java.util.concurrent.TimeUnit; + import org.hamcrest.Matchers; /** @@ -39,7 +41,7 @@ import org.hamcrest.Matchers; */ public class KeycloakSamlAdapterXMLParserTest { - private static final String CURRENT_XSD_LOCATION = "/schema/keycloak_saml_adapter_1_10.xsd"; + private static final String CURRENT_XSD_LOCATION = "/schema/keycloak_saml_adapter_1_11.xsd"; @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -72,6 +74,11 @@ public class KeycloakSamlAdapterXMLParserTest { testValidationValid("keycloak-saml-with-metadata-url.xml"); } + @Test + public void testValidationWithAllowedClockSkew() throws Exception { + testValidationValid("keycloak-saml-with-allowed-clock-skew-with-unit.xml"); + } + @Test public void testValidationKeyInvalid() throws Exception { InputStream schemaIs = KeycloakSamlAdapterV1Parser.class.getResourceAsStream(CURRENT_XSD_LOCATION); @@ -258,4 +265,26 @@ public class KeycloakSamlAdapterXMLParserTest { IDP idp = sp.getIdp(); assertThat(idp.getMetadataUrl(), is("https:///example.com/metadata.xml")); } + + @Test + public void testAllowedClockSkewDefaultUnit() throws Exception { + KeycloakSamlAdapter config = parseKeycloakSamlAdapterConfig("keycloak-saml-with-allowed-clock-skew-default-unit.xml", KeycloakSamlAdapter.class); + assertNotNull(config); + assertThat(config.getSps(), Matchers.contains(instanceOf(SP.class))); + SP sp = config.getSps().get(0); + IDP idp = sp.getIdp(); + assertThat(idp.getAllowedClockSkew(), is(3)); + assertThat(idp.getAllowedClockSkewUnit(), is(TimeUnit.SECONDS)); + } + @Test + public void testAllowedClockSkewWithUnit() throws Exception { + KeycloakSamlAdapter config = parseKeycloakSamlAdapterConfig("keycloak-saml-with-allowed-clock-skew-with-unit.xml", KeycloakSamlAdapter.class); + assertNotNull(config); + assertThat(config.getSps(), Matchers.contains(instanceOf(SP.class))); + SP sp = config.getSps().get(0); + IDP idp = sp.getIdp(); + assertThat(idp.getAllowedClockSkew(), is(3500)); + assertThat(idp.getAllowedClockSkewUnit(), is (TimeUnit.MILLISECONDS)); + } + } diff --git a/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-default-unit.xml b/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-default-unit.xml new file mode 100644 index 0000000000..5ebd377984 --- /dev/null +++ b/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-default-unit.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + private pem + + + public pem + + + + + + + + + + + + + + + cert pem + + + + 3 + + + diff --git a/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-with-unit.xml b/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-with-unit.xml new file mode 100644 index 0000000000..26e2734003 --- /dev/null +++ b/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml-with-allowed-clock-skew-with-unit.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + private pem + + + public pem + + + + + + + + + + + + + + + cert pem + + + + 3500 + + + diff --git a/saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/util/XMLTimeUtil.java b/saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/util/XMLTimeUtil.java index c194eeb282..30d687c333 100755 --- a/saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/util/XMLTimeUtil.java +++ b/saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/util/XMLTimeUtil.java @@ -19,10 +19,9 @@ package org.keycloak.saml.processing.core.saml.v2.util; import org.keycloak.saml.common.PicketLinkLogger; import org.keycloak.saml.common.PicketLinkLoggerFactory; import org.keycloak.saml.common.constants.GeneralConstants; -import org.keycloak.saml.common.exceptions.ConfigurationException; -import org.keycloak.saml.common.exceptions.ParsingException; import org.keycloak.saml.common.util.SecurityActions; import org.keycloak.saml.common.util.SystemPropertiesUtil; +import org.keycloak.common.util.Time; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; @@ -31,6 +30,7 @@ import javax.xml.datatype.Duration; import javax.xml.datatype.XMLGregorianCalendar; import java.util.GregorianCalendar; import java.util.TimeZone; +import java.util.concurrent.TimeUnit; /** * Util class dealing with xml based time @@ -49,8 +49,6 @@ public class XMLTimeUtil { * @param millis * * @return calendar value with the addition - * - * @throws org.keycloak.saml.common.exceptions.ConfigurationException */ public static XMLGregorianCalendar add(XMLGregorianCalendar value, long millis) { if (value == null) { @@ -76,8 +74,6 @@ public class XMLTimeUtil { * @param millis miliseconds entered in a positive value * * @return - * - * @throws ConfigurationException */ public static XMLGregorianCalendar subtract(XMLGregorianCalendar value, long millis) { return add(value, - millis); @@ -91,8 +87,6 @@ public class XMLTimeUtil { * @param timezone * * @return - * - * @throws ConfigurationException */ public static XMLGregorianCalendar getIssueInstant(String timezone) { TimeZone tz = TimeZone.getTimeZone(timezone); @@ -102,6 +96,12 @@ public class XMLTimeUtil { GregorianCalendar gc = new GregorianCalendar(tz); XMLGregorianCalendar xgc = dtf.newXMLGregorianCalendar(gc); + Long offsetMilis = TimeUnit.MILLISECONDS.convert(Time.getOffset(), TimeUnit.SECONDS); + if (offsetMilis != 0) { + if (logger.isDebugEnabled()) logger.debug(XMLTimeUtil.class.getName() + " timeOffset: " + offsetMilis); + xgc.add(parseAsDuration(offsetMilis.toString())); + } + if (logger.isDebugEnabled()) logger.debug(XMLTimeUtil.class.getName() + " issueInstant: " + xgc.toString()); return xgc; } @@ -109,8 +109,6 @@ public class XMLTimeUtil { * Get the current instant of time * * @return - * - * @throws ConfigurationException */ public static XMLGregorianCalendar getIssueInstant() { return getIssueInstant(getCurrentTimeZoneID()); @@ -179,10 +177,8 @@ public class XMLTimeUtil { * @param timeValue * * @return - * - * @throws org.keycloak.saml.common.exceptions.ParsingException */ - public static Duration parseAsDuration(String timeValue) throws ParsingException { + public static Duration parseAsDuration(String timeValue) { if (timeValue == null) { PicketLinkLoggerFactory.getLogger().nullArgumentError("duration time"); } @@ -207,10 +203,8 @@ public class XMLTimeUtil { * @param timeString * * @return - * - * @throws ParsingException */ - public static XMLGregorianCalendar parse(String timeString) throws ParsingException { + public static XMLGregorianCalendar parse(String timeString) { DatatypeFactory factory = DATATYPE_FACTORY.get(); return factory.newXMLGregorianCalendar(timeString); } diff --git a/testsuite/integration-arquillian/servers/app-server/jboss/common/cli/add-adapter-log-level.cli b/testsuite/integration-arquillian/servers/app-server/jboss/common/cli/add-adapter-log-level.cli index 377ae72154..f70a460465 100644 --- a/testsuite/integration-arquillian/servers/app-server/jboss/common/cli/add-adapter-log-level.cli +++ b/testsuite/integration-arquillian/servers/app-server/jboss/common/cli/add-adapter-log-level.cli @@ -1,5 +1,7 @@ embed-server --server-config=${server.config:standalone.xml} /subsystem=logging/logger=org.keycloak.adapters:add(level=DEBUG) +/subsystem=logging/logger=org.keycloak.saml:add(level=DEBUG) +/subsystem=logging/logger=org.keycloak.testsuite.adapter:add(level=DEBUG) /subsystem=logging/logger=org.keycloak.subsystem.adapter:add(level=DEBUG) /subsystem=logging/console-handler=CONSOLE:change-log-level(level=DEBUG) diff --git a/testsuite/integration-arquillian/test-apps/servlets/src/main/java/org/keycloak/testsuite/adapter/servlet/SendUsernameServlet.java b/testsuite/integration-arquillian/test-apps/servlets/src/main/java/org/keycloak/testsuite/adapter/servlet/SendUsernameServlet.java index bfcc9e98a4..513787374d 100755 --- a/testsuite/integration-arquillian/test-apps/servlets/src/main/java/org/keycloak/testsuite/adapter/servlet/SendUsernameServlet.java +++ b/testsuite/integration-arquillian/test-apps/servlets/src/main/java/org/keycloak/testsuite/adapter/servlet/SendUsernameServlet.java @@ -24,7 +24,7 @@ import org.keycloak.adapters.saml.SamlPrincipal; import org.keycloak.adapters.spi.AuthenticationError; import org.keycloak.saml.processing.core.saml.v2.constants.X500SAMLProfileConstants; -import javax.servlet.ServletException; +import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -109,7 +109,7 @@ public class SendUsernameServlet { @Path("error.html") public Response errorPagePost() { authError = (SamlAuthenticationError) httpServletRequest.getAttribute(AuthenticationError.class.getName()); - Integer statusCode = (Integer) httpServletRequest.getAttribute("javax.servlet.error.status_code"); + Integer statusCode = (Integer) httpServletRequest.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); System.out.println("In SendUsername Servlet errorPage() status code: " + statusCode); return Response.ok(getErrorOutput(statusCode)).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML_TYPE + ";charset=UTF-8").build(); diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostClockSkewServlet.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostClockSkewServlet.java new file mode 100644 index 0000000000..9fd3d22261 --- /dev/null +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostClockSkewServlet.java @@ -0,0 +1,36 @@ +/* + * Copyright 2019 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.testsuite.adapter.page; + +import org.jboss.arquillian.container.test.api.OperateOnDeployment; +import org.jboss.arquillian.test.api.ArquillianResource; + +import java.net.URL; + +public class SalesPostClockSkewServlet extends SAMLServlet { + public static final String DEPLOYMENT_NAME = "sales-post-clock-skew"; + + @ArquillianResource + @OperateOnDeployment(DEPLOYMENT_NAME) + private URL url; + + @Override + public URL getInjectedUrl() { + return url; + } +} diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AdapterTestExecutionDecider.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AdapterTestExecutionDecider.java index 2f09115070..257d2a6c73 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AdapterTestExecutionDecider.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AdapterTestExecutionDecider.java @@ -46,7 +46,8 @@ public class AdapterTestExecutionDecider implements TestExecutionDecider { } if (testContext.isAdapterContainerEnabled() || testContext.isAdapterContainerEnabledCluster()) { - if (method.isAnnotationPresent(AppServerContainer.class)) { // taking method level annotation first as it has higher priority + // taking method level annotation first as it has higher priority + if (method.isAnnotationPresent(AppServerContainers.class) || method.isAnnotationPresent(AppServerContainer.class)) { if (getCorrespondingAnnotation(method) == null) { //no corresponding annotation - taking class level annotation if (getCorrespondingAnnotation(testContext.getTestClass()).skip()) { return ExecutionDecision.dontExecute("Skipped by @AppServerContainer class level annotation."); @@ -55,7 +56,8 @@ public class AdapterTestExecutionDecider implements TestExecutionDecider { return ExecutionDecision.dontExecute("Skipped by @AppServerContainer method level annotation."); } } else { //taking class level annotation - if (getCorrespondingAnnotation(testContext.getTestClass()).skip()) { + if (getCorrespondingAnnotation(testContext.getTestClass()) == null || + getCorrespondingAnnotation(testContext.getTestClass()).skip()) { return ExecutionDecision.dontExecute("Skipped by @AppServerContainer class level annotation."); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AppServerTestEnricher.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AppServerTestEnricher.java index 8571a47d75..6a694479a2 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AppServerTestEnricher.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AppServerTestEnricher.java @@ -38,13 +38,15 @@ import org.wildfly.extras.creaper.core.online.OnlineManagementClient; import org.wildfly.extras.creaper.core.online.OnlineOptions; import java.io.IOException; +import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.stream.Collectors; import static org.keycloak.testsuite.arquillian.AuthServerTestEnricher.getAuthServerContextRoot; @@ -63,17 +65,32 @@ public class AppServerTestEnricher { @Inject private Instance testContextInstance; private TestContext testContext; - public static List getAppServerQualifiers(Class testClass) { + public static Set getAppServerQualifiers(Class testClass) { + Set appServerQualifiers = new HashSet<>(); + Class annotatedClass = getNearestSuperclassWithAppServerAnnotation(testClass); - if (annotatedClass == null) return null; // no @AppServerContainer annotation --> no adapter test + if (annotatedClass != null) { - AppServerContainer[] appServerContainers = annotatedClass.getAnnotationsByType(AppServerContainer.class); + AppServerContainer[] appServerContainers = annotatedClass.getAnnotationsByType(AppServerContainer.class); + + for (AppServerContainer appServerContainer : appServerContainers) { + appServerQualifiers.add(appServerContainer.value()); + } - List appServerQualifiers = new ArrayList<>(); - for (AppServerContainer appServerContainer : appServerContainers) { - appServerQualifiers.add(appServerContainer.value()); } + + for (Method method : testClass.getDeclaredMethods()) { + if (method.isAnnotationPresent(AppServerContainers.class)) { + for (AppServerContainer appServerContainer : method.getAnnotation(AppServerContainers.class).value()) { + appServerQualifiers.add(appServerContainer.value()); + } + } + if (method.isAnnotationPresent(AppServerContainer.class)) { + appServerQualifiers.add(method.getAnnotation(AppServerContainer.class).value()); + } + } + return appServerQualifiers; } @@ -115,8 +132,8 @@ public class AppServerTestEnricher { public void updateTestContextWithAppServerInfo(@Observes(precedence = 1) BeforeClass event) { testContext = testContextInstance.get(); - List appServerQualifiers = getAppServerQualifiers(testContext.getTestClass()); - if (appServerQualifiers == null) { // no adapter test + Set appServerQualifiers = getAppServerQualifiers(testContext.getTestClass()); + if (appServerQualifiers.isEmpty()) { // no adapter test log.info("\n\n" + testContext); return; } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/DeploymentTargetModifier.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/DeploymentTargetModifier.java index 39d5ab53c9..9178cc525e 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/DeploymentTargetModifier.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/DeploymentTargetModifier.java @@ -20,6 +20,7 @@ package org.keycloak.testsuite.arquillian; import java.util.ArrayList; import java.util.Objects; import java.util.List; +import java.util.Set; import org.jboss.arquillian.container.spi.client.deployment.DeploymentDescription; import org.jboss.arquillian.container.spi.client.deployment.TargetDescription; import org.jboss.arquillian.core.api.Instance; @@ -60,8 +61,8 @@ public class DeploymentTargetModifier extends AnnotationDeploymentScenarioGenera List deployments = super.generate(testClass); checkTestDeployments(deployments, testClass, context.isAdapterTest()); - List appServerQualifiers = getAppServerQualifiers(testClass.getJavaClass()); - if (appServerQualifiers == null) return deployments; // no adapter test + Set appServerQualifiers = getAppServerQualifiers(testClass.getJavaClass()); + if (appServerQualifiers.isEmpty()) return deployments; // no adapter test String appServerQualifier = appServerQualifiers.stream() .filter(q -> q.contains(AppServerTestEnricher.CURRENT_APP_SERVER)) diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestContext.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestContext.java index d3bb052973..1bc9dc98b7 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestContext.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestContext.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -28,6 +29,7 @@ import org.keycloak.representations.idm.RealmRepresentation; import static org.keycloak.testsuite.arquillian.AppServerTestEnricher.getAppServerQualifiers; import org.keycloak.testsuite.client.KeycloakTestingClient; import org.keycloak.testsuite.util.TestCleanup; +import org.keycloak.testsuite.utils.arquillian.ContainerConstants; /** * @@ -91,20 +93,19 @@ public final class TestContext { } public boolean isAdapterTest() { - return getAppServerQualifiers(testClass) != null; + return !getAppServerQualifiers(testClass).isEmpty(); } public boolean isAdapterContainerEnabled() { if (!isAdapterTest()) return false; //no adapter test - if (appServerInfo == null) return false; - return getAppServerQualifiers(testClass).contains(appServerInfo.getQualifier()); + return getAppServerQualifiers(testClass).contains(ContainerConstants.APP_SERVER_PREFIX + AppServerTestEnricher.CURRENT_APP_SERVER); } public boolean isAdapterContainerEnabledCluster() { if (!isAdapterTest()) return false; //no adapter test if (appServerBackendsInfo.isEmpty()) return false; //no adapter clustered test - List appServerQualifiers = getAppServerQualifiers(testClass); + Set appServerQualifiers = getAppServerQualifiers(testClass); String qualifier = appServerBackendsInfo.stream() .map(ContainerInfo::getQualifier) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java index 9e2e703fdc..6d8708e09c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java @@ -23,6 +23,7 @@ import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.adapter.filter.AdapterActionsFilter; +import org.keycloak.testsuite.util.DroneUtils; import org.keycloak.testsuite.util.WaitUtils; import org.keycloak.testsuite.utils.arquillian.DeploymentArchiveProcessorUtils; import org.keycloak.testsuite.utils.io.IOUtil; @@ -98,6 +99,14 @@ public abstract class AbstractServletsAdapterTest extends AbstractAdapterTest { } public static WebArchive samlServletDeployment(String name, String webXMLPath, Class... servletClasses) { + return samlServletDeployment(name, webXMLPath, null, servletClasses); + } + + public static WebArchive samlServletDeployment(String name, String webXMLPath, Integer clockSkewSec, Class... servletClasses) { + return samlServletDeployment(name, name, webXMLPath, clockSkewSec, servletClasses); + } + + public static WebArchive samlServletDeployment(String name, String customArchiveName, String webXMLPath, Integer clockSkewSec, Class... servletClasses) { String baseSAMLPath = "/adapter-test/keycloak-saml/"; String webInfPath = baseSAMLPath + name + "/WEB-INF/"; @@ -107,15 +116,23 @@ public abstract class AbstractServletsAdapterTest extends AbstractAdapterTest { URL webXML = AbstractServletsAdapterTest.class.getResource(baseSAMLPath + webXMLPath); Assert.assertNotNull("web.xml should be in " + baseSAMLPath + webXMLPath, keycloakSAMLConfig); - WebArchive deployment = ShrinkWrap.create(WebArchive.class, name + ".war") + WebArchive deployment = ShrinkWrap.create(WebArchive.class, customArchiveName + ".war") .addClasses(servletClasses) - .addAsWebInfResource(keycloakSAMLConfig, "keycloak-saml.xml") .addAsWebInfResource(jbossDeploymentStructure, JBOSS_DEPLOYMENT_STRUCTURE_XML); String webXMLContent; try { webXMLContent = IOUtils.toString(webXML.openStream(), Charset.forName("UTF-8")) .replace("%CONTEXT_PATH%", name); + + if (clockSkewSec != null) { + String keycloakSamlXMLContent = IOUtils.toString(keycloakSAMLConfig.openStream(), Charset.forName("UTF-8")) + .replace("%CLOCK_SKEW%", String.valueOf(clockSkewSec)); + deployment.addAsWebInfResource(new StringAsset(keycloakSamlXMLContent), "keycloak-saml.xml"); + } else { + deployment.addAsWebInfResource(keycloakSAMLConfig, "keycloak-saml.xml"); + } + } catch (IOException e) { throw new RuntimeException(e); } @@ -193,9 +210,9 @@ public abstract class AbstractServletsAdapterTest extends AbstractAdapterTest { .queryParam(AdapterActionsFilter.TIME_OFFSET_PARAM, timeOffset) .build().toString(); - driver.navigate().to(timeOffsetUri); + DroneUtils.getCurrentDriver().navigate().to(timeOffsetUri); WaitUtils.waitUntilElement(By.tagName("body")).is().visible(); - String pageSource = driver.getPageSource(); + String pageSource = DroneUtils.getCurrentDriver().getPageSource(); System.out.println(pageSource); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLClockSkewAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLClockSkewAdapterTest.java new file mode 100644 index 0000000000..10eccc813b --- /dev/null +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLClockSkewAdapterTest.java @@ -0,0 +1,167 @@ +/* + * Copyright 2019 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.testsuite.adapter.servlet; + +import java.util.List; +import org.apache.http.util.EntityUtils; +import org.hamcrest.Matcher; +import org.jboss.arquillian.container.test.api.Deployer; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Assert; +import org.junit.Test; +import org.keycloak.adapters.rotation.PublicKeyLocator; +import org.keycloak.representations.idm.RealmRepresentation; +import org.keycloak.testsuite.adapter.AbstractServletsAdapterTest; +import org.keycloak.testsuite.adapter.filter.AdapterActionsFilter; +import org.keycloak.testsuite.arquillian.annotation.AppServerContainer; +import org.keycloak.testsuite.util.SamlClientBuilder; +import org.keycloak.testsuite.utils.arquillian.ContainerConstants; +import org.keycloak.testsuite.utils.io.IOUtil; + +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import org.jboss.arquillian.graphene.page.Page; +import static org.keycloak.testsuite.adapter.AbstractServletsAdapterTest.samlServletDeployment; +import org.keycloak.testsuite.adapter.page.SalesPostClockSkewServlet; +import static org.keycloak.testsuite.util.SamlClient.Binding.POST; + + +@AppServerContainer(ContainerConstants.APP_SERVER_UNDERTOW) +@AppServerContainer(ContainerConstants.APP_SERVER_WILDFLY) +@AppServerContainer(ContainerConstants.APP_SERVER_WILDFLY_DEPRECATED) +@AppServerContainer(ContainerConstants.APP_SERVER_EAP) +@AppServerContainer(ContainerConstants.APP_SERVER_EAP6) +@AppServerContainer(ContainerConstants.APP_SERVER_EAP71) +@AppServerContainer(ContainerConstants.APP_SERVER_JETTY92) +@AppServerContainer(ContainerConstants.APP_SERVER_JETTY93) +@AppServerContainer(ContainerConstants.APP_SERVER_JETTY94) +public class SAMLClockSkewAdapterTest extends AbstractServletsAdapterTest { + + @Page protected SalesPostClockSkewServlet salesPostClockSkewServletPage; + private static final String DEPLOYMENT_NAME_3_SEC = SalesPostClockSkewServlet.DEPLOYMENT_NAME + "_3Sec"; + private static final String DEPLOYMENT_NAME_30_SEC = SalesPostClockSkewServlet.DEPLOYMENT_NAME + "_30Sec"; + + @ArquillianResource private Deployer deployer; + + @Deployment(name = DEPLOYMENT_NAME_3_SEC, managed = false) + protected static WebArchive salesPostClockSkewServlet3Sec() { + return samlServletDeployment(SalesPostClockSkewServlet.DEPLOYMENT_NAME, DEPLOYMENT_NAME_3_SEC, SalesPostClockSkewServlet.DEPLOYMENT_NAME + "/WEB-INF/web.xml", 3, AdapterActionsFilter.class, PublicKeyLocator.class, SendUsernameServlet.class); + } + @Deployment(name = DEPLOYMENT_NAME_30_SEC, managed = false) + protected static WebArchive salesPostClockSkewServlet30Sec() { + return samlServletDeployment(SalesPostClockSkewServlet.DEPLOYMENT_NAME, DEPLOYMENT_NAME_30_SEC, SalesPostClockSkewServlet.DEPLOYMENT_NAME + "/WEB-INF/web.xml", 30, AdapterActionsFilter.class, PublicKeyLocator.class, SendUsernameServlet.class); + } + + @Deployment(name = SalesPostClockSkewServlet.DEPLOYMENT_NAME, managed = false) + protected static WebArchive salesPostClockSkewServlet5Sec() { + return samlServletDeployment(SalesPostClockSkewServlet.DEPLOYMENT_NAME, SalesPostClockSkewServlet.DEPLOYMENT_NAME + "/WEB-INF/web.xml", 5, AdapterActionsFilter.class, PublicKeyLocator.class, SendUsernameServlet.class); + } + + @Override + public void addAdapterTestRealms(List testRealms) { + testRealms.add(IOUtil.loadRealm("/adapter-test/keycloak-saml/testsaml.json")); + } + + private void assertOutcome(int timeOffset, Matcher matcher) throws Exception { + try { + String resultPage = new SamlClientBuilder() + .navigateTo(salesPostClockSkewServletPage.toString()) + .processSamlResponse(POST).build() + .login().user(bburkeUser).build() + .processSamlResponse(POST) + .transformDocument(doc -> { + setAdapterAndServerTimeOffset(timeOffset, salesPostClockSkewServletPage.toString() + "unsecured"); + return doc; + }).build().executeAndTransform(resp -> EntityUtils.toString(resp.getEntity())); + + Assert.assertThat(resultPage, matcher); + } finally { + setAdapterAndServerTimeOffset(0); + } + } + + private void assertTokenIsNotValid(int timeOffset) throws Exception { + deployer.deploy(DEPLOYMENT_NAME_3_SEC); + + try { + assertOutcome(timeOffset, allOf( + not(containsString("request-path: principal=bburke")), + containsString("SAMLRequest"), + containsString("FORM METHOD=\"POST\"") + )); + } finally { + deployer.undeploy(DEPLOYMENT_NAME_3_SEC); + } + } + + @Test + public void testTokenHasExpired() throws Exception { + assertTokenIsNotValid(65); + } + + @Test + public void testTokenIsNotYetValid() throws Exception { + assertTokenIsNotValid(-65); + } + + + @Test + public void testTokenTimeIsValid() throws Exception { + deployer.deploy(DEPLOYMENT_NAME_30_SEC); + + try { + assertOutcome(-10, allOf(containsString("request-path:"), containsString("principal=bburke"))); + } finally { + deployer.undeploy(DEPLOYMENT_NAME_30_SEC); + } + } + + @Test + @AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT7) + @AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT8) + @AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT9) + @AppServerContainer(value = ContainerConstants.APP_SERVER_UNDERTOW, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_WILDFLY, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_WILDFLY_DEPRECATED, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_EAP, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_EAP6, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_EAP71, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_JETTY92, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_JETTY93, skip = true) + @AppServerContainer(value = ContainerConstants.APP_SERVER_JETTY94, skip = true) + public void testClockSkewTomcat() throws Exception { + + /* + * Tomcat by default determines context path from name of hot deployed war, + * because of that we need to have this specific test for tomcat containers + */ + + deployer.deploy(SalesPostClockSkewServlet.DEPLOYMENT_NAME); + + try { + assertOutcome(-4, allOf(containsString("request-path:"), containsString("principal=bburke"))); + assertTokenIsNotValid(65); + assertTokenIsNotValid(-65); + } finally { + deployer.undeploy(SalesPostClockSkewServlet.DEPLOYMENT_NAME); + } + } +} diff --git a/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/keycloak-saml.xml b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/keycloak-saml.xml new file mode 100644 index 0000000000..f26ddcf3d4 --- /dev/null +++ b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/keycloak-saml.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + %CLOCK_SKEW% + + + diff --git a/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/web.xml b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/web.xml new file mode 100644 index 0000000000..5e26dd9de8 --- /dev/null +++ b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-clock-skew/WEB-INF/web.xml @@ -0,0 +1,72 @@ + + + + + + %CONTEXT_PATH% + + + javax.ws.rs.core.Application + 1 + + + javax.ws.rs.core.Application + /* + + + + /error.html + + + + AdapterActionsFilter + org.keycloak.testsuite.adapter.filter.AdapterActionsFilter + + + AdapterActionsFilter + /unsecured/* + + + + + Application + /* + + + manager + + + + + Unsecured + /unsecured/* + + + + + KEYCLOAK-SAML + demo + + + + manager + + diff --git a/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/testsaml.json b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/testsaml.json index c3f17945f9..093311b88a 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/testsaml.json +++ b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/testsaml.json @@ -227,6 +227,20 @@ "saml_idp_initiated_sso_url_name": "sales-post" } }, + { + "clientId": "http://localhost:8280/sales-post-clock-skew/", + "enabled": true, + "fullScopeAllowed": true, + "protocol": "saml", + "baseUrl": "http://localhost:8080/sales-post-clock-skew", + "redirectUris": [ + "http://localhost:8080/sales-post-clock-skew/*" + ], + "attributes": { + "saml.authnstatement": "true", + "saml_idp_initiated_sso_url_name": "sales-post-clock-skew" + } + }, { "clientId": "http://localhost:8280/sales-post-passive/", "enabled": true, diff --git a/testsuite/integration-arquillian/util/src/main/java/org/keycloak/testsuite/utils/undertow/UndertowDeployerHelper.java b/testsuite/integration-arquillian/util/src/main/java/org/keycloak/testsuite/utils/undertow/UndertowDeployerHelper.java index a4f11eeb64..7747d75248 100644 --- a/testsuite/integration-arquillian/util/src/main/java/org/keycloak/testsuite/utils/undertow/UndertowDeployerHelper.java +++ b/testsuite/integration-arquillian/util/src/main/java/org/keycloak/testsuite/utils/undertow/UndertowDeployerHelper.java @@ -31,6 +31,7 @@ import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.Node; import org.jboss.shrinkwrap.api.asset.ClassAsset; +import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -61,13 +62,7 @@ public class UndertowDeployerHelper { public DeploymentInfo getDeploymentInfo(UndertowContainerConfiguration config, WebArchive archive, DeploymentInfo di) { String archiveName = archive.getName(); - - String appName = archive.getName().substring(0, archive.getName().lastIndexOf('.')); - if (appName.contains(System.getProperty("project.version"))) { - appName = archive.getName().substring(0, archive.getName().lastIndexOf("-" + System.getProperty("project.version"))); - } - - String contextPath = "/" + appName; + String contextPath = getContextPath(archive); String appContextUrl = "http://" + config.getBindAddress() + ":" + config.getBindHttpPort() + contextPath; try { @@ -208,4 +203,12 @@ public class UndertowDeployerHelper { } + private String getContextPath(WebArchive archive) { + if (archive.contains("/META-INF/context.xml") && (archive.get("/META-INF/context.xml").getAsset() instanceof StringAsset)) { + StringAsset asset = (StringAsset) archive.get("/META-INF/context.xml").getAsset(); + return asset.getSource().split("path=\"")[1].split("\"")[0]; + } else { + return "/".concat(archive.getName().replace(".war", "")); + } + } }