summaryrefslogtreecommitdiff
path: root/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2
diff options
context:
space:
mode:
Diffstat (limited to 'eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2')
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/AbstractSamlVerificationEngine.java328
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java613
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/Pvp2SProfileCoreSpringResourceProviderTest.java56
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/PvpCoreMessageSourceTest.java43
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/QaaLevelVerifierTest.java147
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineTest.java474
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineWithHsmFacadeTest.java70
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/PostBindingTest.java764
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/RedirectBindingTest.java854
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/SoapBindingTest.java216
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java93
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyMetadataProvider.java80
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/ChainingMetadataTest.java167
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataBuilderTest.java301
-rw-r--r--eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataResolverTest.java742
15 files changed, 4948 insertions, 0 deletions
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/AbstractSamlVerificationEngine.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/AbstractSamlVerificationEngine.java
new file mode 100644
index 00000000..d5186857
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/AbstractSamlVerificationEngine.java
@@ -0,0 +1,328 @@
+package at.gv.egiz.eaaf.modules.pvp2.test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import at.gv.egiz.eaaf.core.api.idp.IConfiguration;
+import at.gv.egiz.eaaf.core.exceptions.EaafException;
+import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException;
+import at.gv.egiz.eaaf.core.impl.data.Pair;
+import at.gv.egiz.eaaf.modules.pvp2.PvpConstants;
+import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2InternalErrorException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest;
+import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer;
+import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SamlVerificationEngine;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyMetadataProvider;
+
+import org.joda.time.DateTime;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.saml.common.xml.SAMLConstants;
+import org.opensaml.saml.saml2.core.Assertion;
+import org.opensaml.saml.saml2.core.AuthnRequest;
+import org.opensaml.saml.saml2.core.EncryptedAssertion;
+import org.opensaml.saml.saml2.core.Issuer;
+import org.opensaml.saml.saml2.core.Response;
+import org.opensaml.saml.saml2.encryption.Encrypter;
+import org.opensaml.saml.saml2.encryption.Encrypter.KeyPlacement;
+import org.opensaml.security.x509.X509Credential;
+import org.opensaml.xmlsec.SecurityConfigurationSupport;
+import org.opensaml.xmlsec.encryption.support.DataEncryptionParameters;
+import org.opensaml.xmlsec.encryption.support.EncryptionException;
+import org.opensaml.xmlsec.encryption.support.KeyEncryptionParameters;
+import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.Assert;
+
+import net.shibboleth.utilities.java.support.xml.XMLParserException;
+
+
+public abstract class AbstractSamlVerificationEngine {
+
+ @Autowired
+ private PvpMetadataResolverFactory metadataResolverFactory;
+ @Autowired
+ private SamlVerificationEngine verifyEngine;
+ @Autowired
+ protected DummyCredentialProvider credentialProvider;
+
+ @Autowired DummyMetadataProvider metadataProvider;
+ @Autowired IConfiguration authConfig;
+
+ /**
+ * JUnit class initializer.
+ *
+ * @throws Exception In case of an OpenSAML3 initialization error
+ */
+ @BeforeClass
+ public static void classInitializer() throws Exception {
+ EaafOpenSaml3xInitializer.eaafInitialize();
+
+ }
+ protected abstract String getMetadataJunitJKeystore();
+
+ protected abstract String getMetadataClassPathEntityPath();
+
+ protected abstract String getAuthnRequestWithoutSigPath();
+
+ protected abstract String getResponseWithSigPath();
+
+ protected abstract String getResponseWithoutSigPath();
+
+
+ @Test
+ public void validateSamlRequestSuccess() throws SecurityException, Exception {
+
+ final String authnReqPath = getAuthnRequestWithoutSigPath();
+ final String metadataPath = getMetadataClassPathEntityPath();
+ final String spEntityId = metadataPath;
+
+ final Pair<AuthnRequest, IPvp2MetadataProvider> inputMsg =
+ initializeAuthnRequest(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final PvpSProfileRequest msg = new PvpSProfileRequest(
+ inputMsg.getFirst(),
+ SAMLConstants.SAML2_POST_BINDING_URI);
+ msg.setEntityID(spEntityId);
+
+ verifyEngine.verify(msg,
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+
+ }
+
+ @Test
+ public void validateSamlRequestWrongSignature() throws SecurityException, Exception {
+
+ final String authnReqPath = getAuthnRequestWithoutSigPath();
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = metadataPath;
+
+ final Pair<AuthnRequest, IPvp2MetadataProvider> inputMsg =
+ initializeAuthnRequest(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ metadataProvider.addMetadataResolverIntoChain(inputMsg.getSecond());
+
+ final PvpSProfileRequest msg = new PvpSProfileRequest(
+ inputMsg.getFirst(),
+ SAMLConstants.SAML2_POST_BINDING_URI);
+ msg.setEntityID(spEntityId);
+
+ try {
+ verifyEngine.verify(msg,
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+ org.junit.Assert.fail("Wrong signature not detected");
+
+ } catch (final Exception e) {
+ Assert.isInstanceOf(InvalidProtocolRequestException.class, e, "Wrong exceptionType");
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.10", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyResponseSuccessTest() throws Pvp2InternalErrorException, SecurityException, Exception {
+ metadataProvider.runGarbageCollector();
+
+ final String authnReqPath = getResponseWithoutSigPath();
+ final String metadataPath = getMetadataClassPathEntityPath();
+ final String spEntityId = metadataPath;
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final PvpSProfileResponse msg = new PvpSProfileResponse(
+ inputMsg.getFirst());
+ msg.setEntityID(spEntityId);
+
+ verifyEngine.verify(msg,
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+
+ }
+
+ @Test
+ public void verifyResponseSuccessSecondTest()
+ throws Pvp2InternalErrorException, SecurityException, Exception {
+
+ final String authnReqPath = getResponseWithoutSigPath();
+ final String metadataPath = getMetadataClassPathEntityPath();
+ final String spEntityId = metadataPath;
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ verifyEngine.verifyIdpResponse(inputMsg.getFirst(),
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+
+ }
+
+ @Test
+ public void verifySpResponse()
+ throws Pvp2InternalErrorException, SecurityException, Exception {
+
+ final String authnReqPath = getResponseWithoutSigPath();
+ final String metadataPath = getMetadataClassPathEntityPath();
+ final String spEntityId = metadataPath;
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ verifyEngine.verifySloResponse(inputMsg.getFirst(),
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+
+ }
+
+ @Test
+ public void verifyResponseWithoutId() throws Pvp2InternalErrorException, SecurityException, Exception {
+
+ final String authnReqPath = getResponseWithSigPath();
+ final String metadataPath = getMetadataClassPathEntityPath();
+ final String spEntityId = metadataPath;
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final PvpSProfileResponse msg = new PvpSProfileResponse(
+ inputMsg.getFirst());
+ msg.setEntityID(spEntityId);
+
+ try {
+ verifyEngine.verify(msg,
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+ org.junit.Assert.fail("Wrong XML schema not detected");
+
+ } catch (final Exception e) {
+ Assert.isInstanceOf(InvalidProtocolRequestException.class, e, "Wrong exceptionType");
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.03", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyResponseWrongTrust() throws Pvp2InternalErrorException, SecurityException, Exception {
+
+ final String authnReqPath = getResponseWithoutSigPath();
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = metadataPath;
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final PvpSProfileResponse msg = new PvpSProfileResponse(
+ inputMsg.getFirst());
+ msg.setEntityID(spEntityId);
+
+ try {
+ verifyEngine.verify(msg,
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+ org.junit.Assert.fail("No TrustedCert not detected");
+
+ } catch (final Exception e) {
+ Assert.isInstanceOf(InvalidProtocolRequestException.class, e, "Wrong exceptionType");
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.10", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ protected Pair<Response, IPvp2MetadataProvider> initializeResponse(String spEntityId, String metadataPath,
+ String authnReqPath, EaafX509Credential credential)
+ throws SamlSigningException, XMLParserException, UnmarshallingException, Pvp2MetadataException {
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ metadataPath, null, "jUnit metadata resolver", null);
+
+ final Response authnReq = (Response) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ AbstractSamlVerificationEngine.class.getResourceAsStream(authnReqPath));
+ authnReq.setIssueInstant(DateTime.now());
+ final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class);
+ issuer.setValue(spEntityId);
+ authnReq.setIssuer(issuer);
+
+ return Pair.newInstance(
+ Saml2Utils.signSamlObject(authnReq, credential, true),
+ mdResolver);
+ }
+
+ protected Pair<AuthnRequest, IPvp2MetadataProvider> initializeAuthnRequest(String spEntityId,
+ String metadataPath, String authnReqPath, EaafX509Credential credential)
+ throws SamlSigningException, CredentialsNotAvailableException,
+ XMLParserException, UnmarshallingException, Pvp2InternalErrorException, Pvp2MetadataException {
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ metadataPath, null, "jUnit metadata resolver", null);
+
+ final AuthnRequest authnReq = (AuthnRequest) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ AbstractSamlVerificationEngine.class.getResourceAsStream(authnReqPath));
+ authnReq.setIssueInstant(DateTime.now());
+ final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class);
+ issuer.setValue(spEntityId);
+ authnReq.setIssuer(issuer);
+
+ return Pair.newInstance(
+ Saml2Utils.signSamlObject(authnReq, credential, true),
+ mdResolver);
+
+ }
+
+ protected static EncryptedAssertion doEncryption(Assertion assertion,
+ X509Credential encryptionCredentials, IConfiguration authConfig)
+ throws Exception {
+ try {
+ final String keyEncAlg = Saml2Utils.getKeyOperationAlgorithmFromCredential(
+ encryptionCredentials,
+ authConfig.getBasicConfiguration(
+ PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_RSA_ALG,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_RSA),
+ authConfig.getBasicConfiguration(
+ PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_EC_ALG,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_EC));
+
+ final DataEncryptionParameters dataEncParams = new DataEncryptionParameters();
+ dataEncParams.setAlgorithm(authConfig.getBasicConfiguration(
+ PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_DATA, PvpConstants.DEFAULT_SYM_ENCRYPTION_METHODE));
+
+ final List<KeyEncryptionParameters> keyEncParamList = new ArrayList<>();
+ final KeyEncryptionParameters keyEncParam = new KeyEncryptionParameters();
+ keyEncParam.setEncryptionCredential(encryptionCredentials);
+ keyEncParam.setAlgorithm(keyEncAlg);
+
+ final KeyInfoGeneratorFactory kigf =
+ SecurityConfigurationSupport.getGlobalEncryptionConfiguration()
+ .getKeyTransportKeyInfoGeneratorManager().getDefaultManager().getFactory(encryptionCredentials);
+ keyEncParam.setKeyInfoGenerator(kigf.newInstance());
+ keyEncParamList.add(keyEncParam);
+
+ final Encrypter samlEncrypter = new Encrypter(dataEncParams, keyEncParamList);
+ samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
+
+ return samlEncrypter.encrypt(assertion);
+
+ } catch (final EncryptionException | SamlSigningException e1) {
+ throw new Exception(e1);
+
+ }
+
+ }
+
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java
new file mode 100644
index 00000000..c784e392
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java
@@ -0,0 +1,613 @@
+package at.gv.egiz.eaaf.modules.pvp2.test;
+
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException;
+import at.gv.egiz.eaaf.core.exceptions.EaafFactoryException;
+import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory;
+import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration;
+import at.gv.egiz.eaaf.core.impl.idp.module.test.DummyAuthConfigMap;
+import at.gv.egiz.eaaf.modules.pvp2.PvpConstants;
+import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.xml.security.algorithms.JCEMapper;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({
+ "/spring/test_eaaf_core_map_config.beans.xml",
+ "/spring/SpringTest-context_lazy.xml",
+ "/spring/eaaf_utils.beans.xml"
+ })
+public class CredentialProviderTest {
+
+ private static final String HSM_FACASE_HOST = "eid.a-sit.at";
+ private static final String HSM_FACASE_PORT = "9050";
+ private static final String HSM_FACASE_SSL_TRUST = "src/test/resources/data/hsm_facade_trust_root.crt";
+ private static final String HSM_FACASE_USERNAME = "authhandler-junit";
+ private static final String HSM_FACASE_PASSWORD = "supersecret123";
+ private static final String PATH_JKS_WITH_TRUST_CERTS = "src/test/resources/data/junit.jks";
+ private static final String PATH_JKS_WITHOUT_TRUST_CERTS = "src/test/resources/data/junit_without_trustcerts.jks";
+
+ private static final String HSM_FACASE_KEYSTORE_NAME = "authhandler";
+
+ private static final String ALIAS_METADATA = "meta";
+ private static final String ALIAS_SIGN = "sig";
+ private static final String ALIAS_ENC = "meta";
+
+ private static final String PASSWORD = "password";
+
+ private static final String HSM_FACADE_KEY_ALIAS = "authhandler-sign";
+
+
+ @Autowired private ApplicationContext context;
+ @Autowired private DummyAuthConfigMap config;
+
+ /**
+ * jUnit test initializer.
+ */
+ @Before
+ public void initialize() {
+ config.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, HSM_FACASE_HOST);
+ config.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, HSM_FACASE_PORT);
+ config.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_SSLTRUST, HSM_FACASE_SSL_TRUST);
+ config.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, HSM_FACASE_USERNAME);
+ config.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, HSM_FACASE_PASSWORD);
+
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_NAME, HSM_FACASE_KEYSTORE_NAME);
+
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_PATH, PATH_JKS_WITH_TRUST_CERTS);
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_PASSWORD, PASSWORD);
+
+ config.removeConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS);
+ config.removeConfigValue(DummyCredentialProvider.KEY_METADATA_PASSWORD);
+
+ config.removeConfigValue(DummyCredentialProvider.KEY_SIGNING_ALIAS);
+ config.removeConfigValue(DummyCredentialProvider.KEY_SIGNING_PASSWORD);
+
+ config.removeConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_ALIAS);
+ config.removeConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_PASSWORD);
+
+ JCEMapper.setProviderId(null);
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void noKeyStoreUrl() {
+ config.removeConfigValue(DummyCredentialProvider.KEYSTORE_PATH);
+ try {
+ context.getBean(DummyCredentialProvider.class);
+ Assert.fail("No KeyStore not detected");
+
+ } catch (final BeansException e) {
+ org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class,
+ e.getCause(), "Wrong exception");
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void noKeyStore() {
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_PATH, "src/test/resources/config/notExist.p12");
+ try {
+ context.getBean(DummyCredentialProvider.class);
+ Assert.fail("No KeyStore not detected");
+
+ } catch (final BeansException e) {
+ org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class,
+ e.getCause(), "Wrong exception");
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void noWrongKeyStorePassword() {
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_PASSWORD, "test");
+ try {
+ context.getBean(DummyCredentialProvider.class);
+ Assert.fail("No KeyStore not detected");
+
+ } catch (final BeansException e) {
+ org.springframework.util.Assert.isInstanceOf(EaafFactoryException.class,
+ e.getCause(), "Wrong exception");
+
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void notKeyConfigurationWrongAlias() {
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMetaDataSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_ALIAS,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMessageSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_ALIAS,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMessageEncryptionCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void notKeyConfigurationWrongPassword() {
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_PASSWORD,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMetaDataSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_PASSWORD,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMessageSigningCredential();
+ Assert.fail("No message signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_PASSWORD,
+ RandomStringUtils.randomAlphabetic(5));
+ final EaafX509Credential encCred = credential.getMessageEncryptionCredential();
+ Assert.assertNull("No encryption credentials not detected", encCred);
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void notKeyConfigurationValidAliasWrongPassword() {
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS,
+ ALIAS_METADATA);
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_PASSWORD,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMetaDataSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_ALIAS,
+ ALIAS_SIGN);
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_PASSWORD,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMessageSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_ALIAS,
+ ALIAS_ENC);
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_PASSWORD,
+ RandomStringUtils.randomAlphabetic(5));
+ credential.getMessageEncryptionCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+ }
+
+ @Test
+ @DirtiesContext
+ public void notKeyConfigurationWrongAliasValidPassword() {
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS,
+ RandomStringUtils.randomAlphabetic(5));
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_PASSWORD,
+ PASSWORD);
+ credential.getMetaDataSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_ALIAS,
+ RandomStringUtils.randomAlphabetic(5));
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_PASSWORD,
+ PASSWORD);
+ credential.getMessageSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_ALIAS,
+ RandomStringUtils.randomAlphabetic(5));
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_PASSWORD,
+ PASSWORD);
+ credential.getMessageEncryptionCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+ }
+
+ @Test
+ @DirtiesContext
+ public void validonfiguration() throws CredentialsNotAvailableException {
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS,
+ ALIAS_METADATA);
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_PASSWORD,
+ PASSWORD);
+
+ checkCredential(credential.getMetaDataSigningCredential(),
+ PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_RSA);
+
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_ALIAS,
+ ALIAS_SIGN);
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_PASSWORD,
+ PASSWORD);
+ checkCredential(credential.getMessageSigningCredential(),
+ PvpConstants.DEFAULT_SIGNING_METHODE_EC,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_EC);
+
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_ALIAS,
+ ALIAS_ENC);
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_PASSWORD,
+ PASSWORD);
+ checkCredential(credential.getMessageEncryptionCredential(),
+ PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_RSA);
+
+
+ final List<X509Certificate> trustCerts = credential.getTrustedCertificates();
+ Assert.assertNotNull("TrustCerts are null", trustCerts);
+ Assert.assertFalse("TrustCerts not empty", trustCerts.isEmpty());
+ Assert.assertEquals("# of Trustcerts", 2, trustCerts.size());
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void validonfigurationWithOutTrustCerts() throws CredentialsNotAvailableException {
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_PATH, PATH_JKS_WITHOUT_TRUST_CERTS);
+
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_SIGNING_RSA_ALG,
+ "RSA-SIG_" + RandomStringUtils.randomAlphabetic(10));
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_SIGNING_EC_ALG,
+ "EC-SIG_" + RandomStringUtils.randomAlphabetic(10));
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_RSA_ALG,
+ "RSA_ENC_" + RandomStringUtils.randomAlphabetic(10));
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_EC_ALG,
+ "EC-ENC_" + RandomStringUtils.randomAlphabetic(10));
+
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS,
+ ALIAS_METADATA);
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_PASSWORD,
+ PASSWORD);
+
+ checkCredential(credential.getMetaDataSigningCredential(),
+ config.getBasicConfiguration(PvpConstants.CONFIG_PROP_SEC_SIGNING_RSA_ALG),
+ config.getBasicConfiguration(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_RSA_ALG));
+
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_ALIAS,
+ ALIAS_SIGN);
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_PASSWORD,
+ PASSWORD);
+ checkCredential(credential.getMessageSigningCredential(),
+ config.getBasicConfiguration(PvpConstants.CONFIG_PROP_SEC_SIGNING_EC_ALG),
+ config.getBasicConfiguration(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_EC_ALG));
+
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_ALIAS,
+ ALIAS_ENC);
+ config.putConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_PASSWORD,
+ PASSWORD);
+ checkCredential(credential.getMessageEncryptionCredential(),
+ config.getBasicConfiguration(PvpConstants.CONFIG_PROP_SEC_SIGNING_RSA_ALG),
+ config.getBasicConfiguration(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_RSA_ALG));
+
+ final List<X509Certificate> trustCerts = credential.getTrustedCertificates();
+ Assert.assertNotNull("TrustCerts are null", trustCerts);
+ Assert.assertTrue("TrustCerts not empty", trustCerts.isEmpty());
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void otherKeyStoreTypeAlreadyLoaded() throws CredentialsNotAvailableException {
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_PATH, PATH_JKS_WITHOUT_TRUST_CERTS);
+
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_SIGNING_RSA_ALG,
+ "RSA-SIG_" + RandomStringUtils.randomAlphabetic(10));
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_SIGNING_EC_ALG,
+ "EC-SIG_" + RandomStringUtils.randomAlphabetic(10));
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_RSA_ALG,
+ "RSA_ENC_" + RandomStringUtils.randomAlphabetic(10));
+ config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_EC_ALG,
+ "EC-ENC_" + RandomStringUtils.randomAlphabetic(10));
+
+ try {
+ JCEMapper.setProviderId(RandomStringUtils.randomAlphabetic(5));
+
+ context.getBean(DummyCredentialProvider.class);
+
+ } catch (final BeansException e) {
+ org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class,
+ e.getCause(), "Wrong exception");
+
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void notKeyConfiguration() {
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ try {
+ credential.getMetaDataSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ credential.getMessageSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ final EaafX509Credential encCred = credential.getMessageEncryptionCredential();
+ Assert.assertNull("No encryption signing credentials not detected", encCred);
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void notKeyConfigurationPkcs12() {
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_PATH,
+ "src/test/resources/data/junit_without_trustcerts.p12");
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ try {
+ credential.getMetaDataSigningCredential();
+ Assert.fail("No Metadata signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ credential.getMessageSigningCredential();
+ Assert.fail("No message signing credentials not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+
+ try {
+ final EaafX509Credential encCred = credential.getMessageEncryptionCredential();
+ Assert.assertNull("No encryption signing credentials not detected", encCred);
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01"));
+
+ }
+ }
+
+ @Test
+ @DirtiesContext
+ public void hasFacadeMissingKeyStoreName() {
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_TYPE,
+ KeyStoreConfiguration.KeyStoreType.HSMFACADE.getKeyStoreType());
+ config.removeConfigValue(DummyCredentialProvider.KEYSTORE_NAME);
+
+ try {
+ context.getBean(DummyCredentialProvider.class);
+ Assert.fail("No KeyStore not detected");
+
+ } catch (final BeansException e) {
+ org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class,
+ e.getCause(), "Wrong exception");
+
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void hasFacadeWrongAlias() {
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_TYPE,
+ KeyStoreConfiguration.KeyStoreType.HSMFACADE.getKeyStoreType());
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_NAME, HSM_FACASE_KEYSTORE_NAME);
+
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS,
+ RandomStringUtils.randomAlphabetic(5));
+
+ try {
+ checkCredential(credential.getMetaDataSigningCredential(),
+ PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_RSA);
+ Assert.fail("Wrong 'alias' not detected");
+
+ } catch (final CredentialsNotAvailableException e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.01", e.getErrorId());
+
+ }
+
+ }
+
+ @Test
+ @DirtiesContext
+ public void validConfigurationHsmFacade() throws CredentialsNotAvailableException {
+
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_TYPE,
+ KeyStoreConfiguration.KeyStoreType.HSMFACADE.getKeyStoreType());
+ config.putConfigValue(DummyCredentialProvider.KEYSTORE_NAME, HSM_FACASE_KEYSTORE_NAME);
+
+ final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class);
+
+ Assert.assertNotNull("Credetialprovider", credential);
+ Assert.assertNotNull("Friendlyname", credential.getFriendlyName());
+
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_ALIAS,
+ HSM_FACADE_KEY_ALIAS);
+ config.putConfigValue(DummyCredentialProvider.KEY_METADATA_PASSWORD,
+ PASSWORD);
+
+
+ checkCredential(credential.getMetaDataSigningCredential(),
+ PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_RSA);
+
+ config.putConfigValue(DummyCredentialProvider.KEY_SIGNING_ALIAS,
+ HSM_FACADE_KEY_ALIAS);
+
+ checkCredential(credential.getMessageSigningCredential(),
+ PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE_RSA);
+
+
+ final List<X509Certificate> trustCerts = credential.getTrustedCertificates();
+ Assert.assertNotNull("TrustCerts are null", trustCerts);
+ Assert.assertTrue("TrustCerts not empty", trustCerts.isEmpty());
+
+ }
+
+
+ private void checkCredential(EaafX509Credential metaDataSigningCredential, String sigAlg, String keyEncAlg) {
+ Assert.assertNotNull("No metadata signing credentials", metaDataSigningCredential);
+ Assert.assertNotNull("SigAlg is null",
+ metaDataSigningCredential.getSignatureAlgorithmForSigning());
+ Assert.assertNotNull("KeyEncAlg is null",
+ metaDataSigningCredential.getKeyEncryptionAlgorithmForDataEncryption());
+ Assert.assertFalse("SigAlg is empty",
+ metaDataSigningCredential.getSignatureAlgorithmForSigning().isEmpty());
+ Assert.assertFalse("KeyEncAlg is empty",
+ metaDataSigningCredential.getKeyEncryptionAlgorithmForDataEncryption().isEmpty());
+
+ Assert.assertEquals("Wrong SigAlg", sigAlg,
+ metaDataSigningCredential.getSignatureAlgorithmForSigning());
+ Assert.assertEquals("Wrong KeyEncAlg", keyEncAlg,
+ metaDataSigningCredential.getKeyEncryptionAlgorithmForDataEncryption());
+
+ }
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/Pvp2SProfileCoreSpringResourceProviderTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/Pvp2SProfileCoreSpringResourceProviderTest.java
new file mode 100644
index 00000000..67c59dec
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/Pvp2SProfileCoreSpringResourceProviderTest.java
@@ -0,0 +1,56 @@
+package at.gv.egiz.eaaf.modules.pvp2.test;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.io.IOUtils;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.springframework.core.io.Resource;
+
+import at.gv.egiz.eaaf.core.test.TestConstants;
+import at.gv.egiz.eaaf.modules.pvp2.Pvp2SProfileCoreSpringResourceProvider;
+
+
+
+@RunWith(BlockJUnit4ClassRunner.class)
+public class Pvp2SProfileCoreSpringResourceProviderTest {
+
+ @Test
+ public void testSpringConfig() {
+ final Pvp2SProfileCoreSpringResourceProvider test =
+ new Pvp2SProfileCoreSpringResourceProvider();
+ for (final Resource el : test.getResourcesToLoad()) {
+ try {
+ IOUtils.toByteArray(el.getInputStream());
+
+ } catch (final IOException e) {
+ Assert.fail("Ressouce: " + el.getFilename() + " not found");
+ }
+
+ }
+
+ Assert.assertNotNull("no Name", test.getName());
+ Assert.assertNull("Find package definitions", test.getPackagesToScan());
+
+ }
+
+ @Test
+ public void testSpILoaderConfig() {
+ final InputStream el = this.getClass().getResourceAsStream(TestConstants.TEST_SPI_LOADER_PATH);
+ try {
+ final String spiFile = IOUtils.toString(el, "UTF-8");
+
+ Assert.assertEquals("Wrong classpath in SPI file",
+ Pvp2SProfileCoreSpringResourceProvider.class.getName(), spiFile);
+
+
+ } catch (final IOException e) {
+ Assert.fail("Ressouce: " + TestConstants.TEST_SPI_LOADER_PATH + " not found");
+
+ }
+ }
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/PvpCoreMessageSourceTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/PvpCoreMessageSourceTest.java
new file mode 100644
index 00000000..b94ed8cc
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/PvpCoreMessageSourceTest.java
@@ -0,0 +1,43 @@
+package at.gv.egiz.eaaf.modules.pvp2.test;
+
+import java.util.List;
+
+import at.gv.egiz.eaaf.core.api.logging.IMessageSourceLocation;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.ResourceLoader;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({ "/spring/test_eaaf_pvp.beans.xml",
+"/spring/test_eaaf_core_spring_config.beans.xml",
+"/spring/eaaf_utils.beans.xml" })
+@TestPropertySource(locations = { "/config/config_1.props" })
+public class PvpCoreMessageSourceTest {
+
+ @Autowired
+ private ResourceLoader loader;
+ @Autowired(required = false)
+ private List<IMessageSourceLocation> messageSources;
+
+ @Test
+ public void checkMessageSources() {
+ Assert.assertNotNull("No messageSource", messageSources);
+
+ for (final IMessageSourceLocation messageSource : messageSources) {
+ Assert.assertNotNull("No sourcePath", messageSource.getMessageSourceLocation());
+
+ for (final String el : messageSource.getMessageSourceLocation()) {
+ final Resource messages = loader.getResource(el + ".properties");
+ Assert.assertTrue("Source not exist", messages.exists());
+
+ }
+ }
+ }
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/QaaLevelVerifierTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/QaaLevelVerifierTest.java
new file mode 100644
index 00000000..44cdf111
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/QaaLevelVerifierTest.java
@@ -0,0 +1,147 @@
+package at.gv.egiz.eaaf.modules.pvp2.test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.BlockJUnit4ClassRunner;
+
+import at.gv.egiz.eaaf.core.api.data.EaafConstants;
+import at.gv.egiz.eaaf.modules.pvp2.exception.QaaNotAllowedException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.utils.QaaLevelVerifier;
+
+@RunWith(BlockJUnit4ClassRunner.class)
+public class QaaLevelVerifierTest {
+
+ QaaLevelVerifier verifyer = new QaaLevelVerifier();
+
+ @Test
+ public void matchingModeUnknown() {
+ String matchingMode = "notExist";
+ List<String> requiredLoAs = Arrays.asList(EaafConstants.EIDAS_LOA_SUBSTANTIAL);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_LOW, requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel("not_exist", requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ }
+
+ @Test
+ public void matchingMinimumRequiredLow() throws QaaNotAllowedException {
+ String matchingMode = EaafConstants.EIDAS_LOA_MATCHING_MINIMUM;
+ List<String> requiredLoAs = Arrays.asList(EaafConstants.EIDAS_LOA_LOW);
+
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_LOW, requiredLoAs, matchingMode);
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_SUBSTANTIAL, requiredLoAs, matchingMode);
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_HIGH, requiredLoAs, matchingMode);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel("not_exist", requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ }
+
+ @Test
+ public void matchingMinimumRequiredSubstantial() throws QaaNotAllowedException {
+ String matchingMode = EaafConstants.EIDAS_LOA_MATCHING_MINIMUM;
+ List<String> requiredLoAs = Arrays.asList(EaafConstants.EIDAS_LOA_SUBSTANTIAL);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_LOW, requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_SUBSTANTIAL, requiredLoAs, matchingMode);
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_HIGH, requiredLoAs, matchingMode);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel("not_exist", requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ }
+
+ @Test
+ public void matchingMinimumRequiredHigh() throws QaaNotAllowedException {
+ String matchingMode = EaafConstants.EIDAS_LOA_MATCHING_MINIMUM;
+ List<String> requiredLoAs = Arrays.asList(EaafConstants.EIDAS_LOA_HIGH);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_LOW, requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_SUBSTANTIAL, requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_HIGH, requiredLoAs, matchingMode);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel("not_exist", requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ }
+
+ @Test
+ public void matchingExact1() throws QaaNotAllowedException {
+ String matchingMode = EaafConstants.EIDAS_LOA_MATCHING_EXACT;
+ List<String> requiredLoAs = Arrays.asList(EaafConstants.EIDAS_LOA_SUBSTANTIAL, EaafConstants.EIDAS_LOA_LOW);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_HIGH, requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_LOW, requiredLoAs, matchingMode);
+ QaaLevelVerifier.verifyQaaLevel(EaafConstants.EIDAS_LOA_SUBSTANTIAL, requiredLoAs, matchingMode);
+
+ try {
+ QaaLevelVerifier.verifyQaaLevel("not_exist", requiredLoAs, matchingMode);
+ Assert.fail("LoA should not be allowed");
+
+ } catch (QaaNotAllowedException e) {
+
+ }
+
+ }
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineTest.java
new file mode 100644
index 00000000..64bfb8f6
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineTest.java
@@ -0,0 +1,474 @@
+package at.gv.egiz.eaaf.modules.pvp2.test;
+
+import at.gv.egiz.eaaf.core.api.idp.IConfiguration;
+import at.gv.egiz.eaaf.core.exceptions.EaafException;
+import at.gv.egiz.eaaf.core.exceptions.EaafProtocolException;
+import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException;
+import at.gv.egiz.eaaf.core.impl.data.Pair;
+import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlAssertionValidationExeption;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SamlVerificationEngine;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyMetadataProvider;
+
+import org.joda.time.DateTime;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.saml.common.xml.SAMLConstants;
+import org.opensaml.saml.saml2.core.Assertion;
+import org.opensaml.saml.saml2.core.AuthnRequest;
+import org.opensaml.saml.saml2.core.EncryptedAssertion;
+import org.opensaml.saml.saml2.core.Response;
+import org.opensaml.saml.saml2.core.StatusCode;
+import org.opensaml.xmlsec.signature.support.SignatureConstants;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.util.Assert;
+import org.w3c.dom.Element;
+
+import net.shibboleth.utilities.java.support.xml.XMLParserException;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({ "/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml" })
+@TestPropertySource(locations = { "/config/config_1.props" })
+public class SamlVerificationEngineTest extends AbstractSamlVerificationEngine {
+
+ @Autowired
+ private SamlVerificationEngine verifyEngine;
+ @Autowired
+ private DummyCredentialProvider credentialProvider;
+
+ @Autowired DummyMetadataProvider metadataProvider;
+ @Autowired IConfiguration authConfig;
+
+ @Override
+ protected String getMetadataClassPathEntityPath() {
+ return "classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml";
+
+ }
+
+ @Override
+ protected String getMetadataJunitJKeystore() {
+ return "classpath:/data/pvp_metadata_junit_keystore.xml";
+ }
+
+ @Override
+ protected String getAuthnRequestWithoutSigPath() {
+ return "/data/AuthRequest_without_sig_1.xml";
+
+ }
+
+ @Override
+ protected String getResponseWithSigPath() {
+ return "/data/Response_with_sig_1.xml";
+ }
+
+ @Override
+ protected String getResponseWithoutSigPath() {
+ return "/data/Response_without_sig_1.xml";
+ }
+
+ @Test
+ public void validateSamlRequestWrongSignatureAlg() throws SecurityException, Exception {
+
+ final String authnReqPath = getAuthnRequestWithoutSigPath();
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = metadataPath;
+
+ metadataProvider.runGarbageCollector();
+
+ final EaafX509Credential cred = credentialProvider.getMetaDataSigningCredential();
+ cred.setSignatureAlgorithmForSigning(SignatureConstants.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5);
+ final Pair<AuthnRequest, IPvp2MetadataProvider> inputMsg =
+ initializeAuthnRequest(spEntityId, metadataPath, authnReqPath,
+ cred);
+
+ final PvpSProfileRequest msg = new PvpSProfileRequest(
+ inputMsg.getFirst(),
+ SAMLConstants.SAML2_POST_BINDING_URI);
+ msg.setEntityID(spEntityId);
+
+ try {
+ verifyEngine.verify(msg,
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+ org.junit.Assert.fail("Wrong SigAlg not detected");
+
+ } catch (final Exception e) {
+ Assert.isInstanceOf(EaafProtocolException.class, e, "Wrong exceptionType");
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.99", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void validateSamlInvalidRequest() throws SecurityException, Exception {
+
+ final String authnReqPath = "/data/AuthRequest_without_sig_missing_id.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = metadataPath;
+
+ final Pair<AuthnRequest, IPvp2MetadataProvider> inputMsg =
+ initializeAuthnRequest(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ metadataProvider.addMetadataResolverIntoChain(inputMsg.getSecond());
+
+ final PvpSProfileRequest msg = new PvpSProfileRequest(
+ inputMsg.getFirst(),
+ SAMLConstants.SAML2_POST_BINDING_URI);
+ msg.setEntityID(spEntityId);
+
+ try {
+ verifyEngine.verify(msg,
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider));
+ org.junit.Assert.fail("invalid request not detected");
+
+ } catch (final Exception e) {
+ Assert.isInstanceOf(InvalidProtocolRequestException.class, e, "Wrong exceptionType");
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.03", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionSucessNotEncrypted() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ verifyEngine.validateAssertion(inputMsg.getFirst(), credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", false);
+
+
+ }
+
+ @Test
+ public void verifyAssertionWrongAudiency() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+ try {
+ verifyEngine.validateAssertion(inputMsg.getFirst(), credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", false);
+ org.junit.Assert.fail("Wrong Audiency not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.15", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionWrongStatusCode() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getStatus().getStatusCode().setValue(StatusCode.RESPONDER);
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", false);
+ org.junit.Assert.fail("Wrong StatusCode not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.17", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionWrongIssueInstant() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.setIssueInstant(DateTime.now().plusMinutes(10));
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", true);
+ org.junit.Assert.fail("Wrong date not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.14", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionNoContitions() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getAssertions().get(0).setConditions(null);
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", true);
+ org.junit.Assert.fail("Wrong date not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.15", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionWrongContitions() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", true);
+ org.junit.Assert.fail("Wrong date not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.15", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionWrongContitionsAudienceRestrictions() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getAssertions().get(0).getConditions().setNotBefore(DateTime.now());
+ response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(15));
+ response.getAssertions().get(0).getConditions().getAudienceRestrictions().clear();
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", true);
+ org.junit.Assert.fail("Wrong date not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.15", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionWrongContitionsNotBefore() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getAssertions().get(0).getConditions().setNotBefore(DateTime.now().plusMinutes(10));
+ response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(15));
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", true);
+ org.junit.Assert.fail("Wrong date not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.15", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionWrongContitionsNotOnOrAfter() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getAssertions().get(0).getConditions().setNotBefore(DateTime.now());
+ response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().minusMinutes(5));
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", true);
+ org.junit.Assert.fail("Wrong date not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.15", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyAssertionValidContitions() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getAssertions().get(0).getConditions().setNotBefore(DateTime.now());
+ response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5));
+
+
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", true);
+
+ }
+
+ @Test
+ public void verifyEncAssertionWrongKey() throws SamlSigningException, Pvp2MetadataException,
+ CredentialsNotAvailableException, XMLParserException, UnmarshallingException, SamlAssertionValidationExeption {
+ final String authnReqPath = "/data/Asserion_enc_no_key.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://eid.a-sit.at/Shibboleth.sso/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ try {
+ verifyEngine.validateAssertion(inputMsg.getFirst(), credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", false);
+ org.junit.Assert.fail("Wrong date not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.16", ((EaafException) e).getErrorId());
+
+ }
+ }
+
+ @Test
+ public void verifyEncAssertion() throws Exception {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getAssertions().get(0).getConditions().setNotBefore(DateTime.now());
+ response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5));
+
+ final Element secAssertionElement = XMLObjectSupport.marshall(response.getAssertions().get(0));
+
+ secAssertionElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xs", "http://www.w3.org/2001/XMLSchema");
+ final Assertion secAssertion = (Assertion) XMLObjectSupport.getUnmarshaller(secAssertionElement)
+ .unmarshall(secAssertionElement);
+
+ final EncryptedAssertion encAsserton = doEncryption(secAssertion,
+ credentialProvider.getMetaDataSigningCredential(),
+ authConfig);
+ response.getEncryptedAssertions().add(encAsserton);
+
+
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", false);
+
+ org.junit.Assert.assertEquals("Assertions not match", 2, response.getAssertions().size());
+
+ }
+
+ @Test
+ public void verifyEncAssertionWrongSchema() throws Exception {
+ final String authnReqPath = "/data/Response_without_sig_classpath_entityid.xml";
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = "https://demo.egiz.gv.at/demoportal_demologin/";
+
+ final Pair<Response, IPvp2MetadataProvider> inputMsg =
+ initializeResponse(spEntityId, metadataPath, authnReqPath,
+ credentialProvider.getMetaDataSigningCredential());
+
+ final Response response = inputMsg.getFirst();
+ response.getAssertions().get(0).getConditions().setNotBefore(DateTime.now());
+ response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5));
+
+ final Element secAssertionElement = XMLObjectSupport.marshall(response.getAssertions().get(0));
+
+ final Assertion secAssertion = (Assertion) XMLObjectSupport.getUnmarshaller(secAssertionElement)
+ .unmarshall(secAssertionElement);
+
+ final EncryptedAssertion encAsserton = doEncryption(secAssertion,
+ credentialProvider.getMetaDataSigningCredential(),
+ authConfig);
+ response.getEncryptedAssertions().add(encAsserton);
+
+ try {
+ verifyEngine.validateAssertion(response, credentialProvider.getMetaDataSigningCredential(),
+ spEntityId, "jUnit Test", false);
+
+ org.junit.Assert.fail("Wrong XML Schema not detected");
+
+ } catch (final SamlAssertionValidationExeption e) {
+ org.junit.Assert.assertEquals("Wrong errorcode", "internal.pvp.15", ((EaafException) e).getErrorId());
+
+ }
+
+ }
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineWithHsmFacadeTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineWithHsmFacadeTest.java
new file mode 100644
index 00000000..5b06a73f
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/SamlVerificationEngineWithHsmFacadeTest.java
@@ -0,0 +1,70 @@
+package at.gv.egiz.eaaf.modules.pvp2.test;
+
+import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.xmlsec.signature.support.SignatureConstants;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({ "/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml" })
+@TestPropertySource(locations = { "/config/config_3.props" })
+public class SamlVerificationEngineWithHsmFacadeTest extends AbstractSamlVerificationEngine {
+
+ @Override
+ protected String getMetadataClassPathEntityPath() {
+ return "classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml";
+
+ }
+
+ @Override
+ protected String getMetadataJunitJKeystore() {
+ return "classpath:/data/pvp_metadata_junit_keystore.xml";
+ }
+
+ @Override
+ protected String getAuthnRequestWithoutSigPath() {
+ return "/data/AuthRequest_without_sig_1.xml";
+
+ }
+
+ @Override
+ protected String getResponseWithSigPath() {
+ return "/data/Response_with_sig_1.xml";
+ }
+
+ @Override
+ protected String getResponseWithoutSigPath() {
+ return "/data/Response_without_sig_1.xml";
+ }
+
+ @Test
+ public void validateSamlRequestWrongSignatureAlg() throws SecurityException, Exception {
+
+ final String authnReqPath = getAuthnRequestWithoutSigPath();
+ final String metadataPath = getMetadataJunitJKeystore();
+ final String spEntityId = metadataPath;
+
+ metadataProvider.runGarbageCollector();
+
+ final EaafX509Credential cred = credentialProvider.getMetaDataSigningCredential();
+ cred.setSignatureAlgorithmForSigning(SignatureConstants.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5);
+ try {
+ initializeAuthnRequest(spEntityId, metadataPath, authnReqPath,
+ cred);
+ org.junit.Assert.fail("Wrong SigAlg not detected");
+
+ } catch (final SamlSigningException e) {
+ org.junit.Assert.assertEquals("Wrong errorCode", "internal.pvp.96", e.getErrorId());
+
+ }
+ }
+
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/PostBindingTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/PostBindingTest.java
new file mode 100644
index 00000000..147199a5
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/PostBindingTest.java
@@ -0,0 +1,764 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.binding;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+import java.util.Map;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import at.gv.egiz.eaaf.core.api.IRequest;
+import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiBuilderConfiguration;
+import at.gv.egiz.eaaf.core.impl.idp.module.gui.DummyGuiBuilderConfigurationFactory;
+import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl;
+import at.gv.egiz.eaaf.core.impl.utils.DomUtils;
+import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory;
+import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential;
+import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute;
+import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlMessageValidationException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding;
+import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage;
+import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest;
+import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer;
+import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EaafUriCompare;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+import at.gv.egiz.eaaf.modules.pvp2.test.metadata.MetadataResolverTest;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.joda.time.DateTime;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.core.xml.XMLObject;
+import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
+import org.opensaml.core.xml.io.MarshallingException;
+import org.opensaml.core.xml.io.Unmarshaller;
+import org.opensaml.core.xml.io.UnmarshallerFactory;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.schema.XSString;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.messaging.decoder.MessageDecodingException;
+import org.opensaml.messaging.encoder.MessageEncodingException;
+import org.opensaml.saml.common.SignableSAMLObject;
+import org.opensaml.saml.saml2.core.AuthnRequest;
+import org.opensaml.saml.saml2.core.Issuer;
+import org.opensaml.saml.saml2.core.RequestAbstractType;
+import org.opensaml.saml.saml2.core.StatusResponseType;
+import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+import net.shibboleth.utilities.java.support.net.URIComparator;
+import net.shibboleth.utilities.java.support.xml.SerializeSupport;
+import net.shibboleth.utilities.java.support.xml.XMLParserException;
+import okhttp3.HttpUrl;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml"})
+@TestPropertySource(locations = {"/config/config_1.props"})
+public class PostBindingTest {
+
+ public static final String HTTP_FORM_RELAYSTATE = "RelayState=";
+ public static final String HTTP_FORM_SAMLREQ = "SAMLRequest=";
+ public static final String HTTP_FORM_SAMLRESP = "SAMLResponse=";
+
+ @Autowired private PostBinding bindingImpl;
+ @Autowired private DummyCredentialProvider credentialProvider;
+ @Autowired private DummyGuiBuilderConfigurationFactory guiBuilderFactory;
+ @Autowired private PvpMetadataResolverFactory metadataResolverFactory;
+ @Autowired private IHttpClientFactory httpClientFactory;
+
+ private static MockWebServer mockWebServer;
+ private static HttpUrl mockServerUrl;
+
+ protected MockHttpServletRequest httpReq;
+ protected MockHttpServletResponse httpResp;
+ protected IRequest pendingReq;
+
+ /**
+ * JUnit class initializer.
+ *
+ * @throws Exception In case of an OpenSAML3 initialization error
+ */
+ @BeforeClass
+ public static void classInitializer() throws Exception {
+ EaafOpenSaml3xInitializer.eaafInitialize();
+
+ mockWebServer = new MockWebServer();
+ mockServerUrl = mockWebServer.url("/sp/metadata");
+ }
+
+ /**
+ * Test initializer.
+ *
+ */
+ @Before
+ public void initialize() {
+ httpReq = new MockHttpServletRequest();
+ httpResp = new MockHttpServletResponse();
+
+ pendingReq = new TestRequestImpl();
+
+ }
+
+ @Test
+ public void checkCanHandle() {
+ httpReq.setMethod("POST");
+ Assert.assertTrue("Wrong canHandle result", bindingImpl.handleDecode("Post", httpReq));
+ Assert.assertFalse("Wrong canHandle result", bindingImpl.handleDecode("Redirect", httpReq));
+
+ httpReq.setMethod("GET");
+ Assert.assertFalse("Wrong canHandle result", bindingImpl.handleDecode("Post", httpReq));
+ Assert.assertFalse("Wrong canHandle result", bindingImpl.handleDecode("Redirect", httpReq));
+ }
+
+ @Test
+ public void wrongPostBindingEncoding() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2MetadataException {
+ final String serviceUrl = "https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp2/post";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final String b64AuthnReq = Base64.getEncoder().encodeToString(IOUtils.toByteArray(
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml")));
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+ httpReq.setParameter("SAMLEncoding", RandomStringUtils.randomAlphabetic(5));
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+ Assert.fail("Missing signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.02", e.getErrorId());
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestWrongEndpoint() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2MetadataException {
+ final String serviceUrl = "https://wrongEndpoint/pvp2/post";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final String b64AuthnReq = Base64.getEncoder().encodeToString(IOUtils.toByteArray(
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_with_sig_1.xml")));
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+ Assert.fail("Wrong http end-point not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.11", e.getErrorId());
+ Assert.assertNotNull("Parameters null", e.getParams());
+ Assert.assertEquals("Wrong numer of parameters", 1, e.getParams().length);
+
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestMissingSignature() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2MetadataException {
+ final String serviceUrl = "https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp2/post";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final String b64AuthnReq = Base64.getEncoder().encodeToString(IOUtils.toByteArray(
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml")));
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+ Assert.fail("Missing signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.02", e.getErrorId());
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestWrongSignature() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2Exception {
+ final String serviceUrl = "https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp2/post";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final String b64AuthnReq = Base64.getEncoder().encodeToString(IOUtils.toByteArray(
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_with_sig_1.xml")));
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+ Assert.fail("Invalid signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ org.springframework.util.Assert.isInstanceOf(SamlSigningException.class, e, "Wrong Exception type");
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.10", e.getErrorId());
+ Assert.assertNotNull("No error params", e.getParams());
+ Assert.assertEquals("Wrong param size", 1, e.getParams().length);
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestMsgExpired() throws MessageDecodingException, SecurityException, IOException, Pvp2Exception {
+ final String serviceUrl = "https://eidas-test.bmi.gv.at/ms_connector/pvp/post";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_moaid_test.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final String b64AuthnReq = new String(IOUtils.toByteArray(
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_withsig_expired.b64")), "UTF-8");
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+ Assert.fail("Expired msg not detected");
+
+ } catch (final Pvp2Exception e) {
+ org.springframework.util.Assert.isInstanceOf(SamlMessageValidationException.class, e, "Wrong Exception type");
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.11", e.getErrorId());
+ Assert.assertNotNull("No error params", e.getParams());
+ Assert.assertEquals("Wrong param size", 1, e.getParams().length);
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestSuccessMetadataReloadRequired() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2Exception, CredentialsNotAvailableException, XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+
+ final String b64AuthnReq = generateSaml2AuthnRequest(
+ credentialProvider.getMetaDataSigningCredential());
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_wrong_sig.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_junit_keystore.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ null, "jUnit test", httpClientFactory.getHttpClient());
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNull("RelayState not null", msg.getRelayState());
+ Assert.assertNotNull("AuthnReq is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg.getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ }
+
+ @Test
+ public void decodeRequestSuccessWithRelayStateRsaSig() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2Exception, CredentialsNotAvailableException, XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = RandomStringUtils.randomAlphanumeric(10);
+
+ final String b64AuthnReq = generateSaml2AuthnRequest(
+ credentialProvider.getMetaDataSigningCredential());
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+ httpReq.addParameter("RelayState", relayState);
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNotNull("RelayState is not null", msg.getRelayState());
+ Assert.assertEquals("RelayState not match", relayState, msg.getRelayState());
+ Assert.assertNotNull("AuthnReq is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg.getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ }
+
+ @Test
+ public void decodeRequestSuccessWithRequestAttributes() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2Exception, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException {
+ final String serviceUrl = "https://eidas-test.bmi.gv.at/ms_connector/pvp/post";
+ final String relayState = RandomStringUtils.randomAlphanumeric(10);
+
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/eIDAS_connector_authn.xml"));
+ authnReq.setIssueInstant(DateTime.now());
+ final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class);
+ issuer.setValue("https://demo.egiz.gv.at/demoportal_demologin/");
+ authnReq.setIssuer(issuer);
+
+ final RequestAbstractType signedAuthn = Saml2Utils.signSamlObject(authnReq, credentialProvider.getMessageSigningCredential(), true);
+ final Element signedElement = XMLObjectSupport.getMarshaller(signedAuthn).marshall(signedAuthn);
+ final String b64AuthnReq =
+ Base64.getEncoder().encodeToString(SerializeSupport.nodeToString(signedElement).getBytes("UTF-8"));
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+ httpReq.addParameter("RelayState", relayState);
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNotNull("RelayState is not null", msg.getRelayState());
+ Assert.assertEquals("RelayState not match", relayState, msg.getRelayState());
+ Assert.assertNotNull("AuthnReq is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg.getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ org.springframework.util.Assert.isInstanceOf(PvpSProfileRequest.class, msg, "Inbound message is of wrong type");
+ org.springframework.util.Assert.isInstanceOf(AuthnRequest.class, ((PvpSProfileRequest)msg).getSamlRequest(),
+ "Inbound message is of wrong type");
+
+ final AuthnRequest parsedAuthnReq = (AuthnRequest)((PvpSProfileRequest)msg).getSamlRequest();
+ Assert.assertNotNull("No extension", parsedAuthnReq.getExtensions());
+ Assert.assertNotNull("No extension child", parsedAuthnReq.getExtensions().getUnknownXMLObjects());
+ Assert.assertEquals("extension child size", 1, parsedAuthnReq.getExtensions().getUnknownXMLObjects().size());
+
+ final XMLObject reqAttrs = parsedAuthnReq.getExtensions().getUnknownXMLObjects().get(0);
+ org.springframework.util.Assert.isInstanceOf(EaafRequestedAttributes.class, reqAttrs, "Wrong requested Attributes type");
+ final EaafRequestedAttributes eaafReqAttrs = (EaafRequestedAttributes) reqAttrs;
+ Assert.assertNotNull("Req attr is null", eaafReqAttrs.getAttributes());
+ Assert.assertFalse("Req attr is empty", eaafReqAttrs.getAttributes().isEmpty());
+ Assert.assertEquals("Req attr size", 1, eaafReqAttrs.getAttributes().size());
+
+ final EaafRequestedAttribute eaafReqAttr = eaafReqAttrs.getAttributes().get(0);
+ Assert.assertNotNull("Req Attibute is null", eaafReqAttr);
+ Assert.assertEquals("Req. Attr. Friendlyname", "EID-SECTOR-FOR-IDENTIFIER", eaafReqAttr.getFriendlyName());
+ Assert.assertEquals("Req. Attr. Name", "urn:oid:1.2.40.0.10.2.1.1.261.34", eaafReqAttr.getName());
+
+ Assert.assertEquals("Req. Attr. Value size", 1, eaafReqAttr.getAttributeValues().size());
+ org.springframework.util.Assert.isInstanceOf(XSString.class, eaafReqAttr.getAttributeValues().get(0),
+ "Wrong requested Attributes Value type");
+ Assert.assertEquals("Req. Attr. Value", "urn:publicid:gv.at:cdid+BF", ((XSString)eaafReqAttr.getAttributeValues().get(0)).getValue());
+
+ }
+
+ @Test
+ public void decodeRequestSuccessWithoutRelayStateEcdsaSig() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2Exception, CredentialsNotAvailableException, XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+
+ final String b64AuthnReq = generateSaml2AuthnRequest(
+ credentialProvider.getMessageSigningCredential());
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNull("RelayState is not null", msg.getRelayState());
+ Assert.assertNotNull("AuthnReq is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg.getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ //check if reconstraction from serialized form work well
+ ((InboundMessage)msg).setSamlMessage(null);
+ try {
+ Assert.assertNotNull("AuthnReq is null", msg.getInboundMessage());
+
+ } catch (final RuntimeException e) { }
+
+ }
+
+ @Test
+ public void decodeResponseSuccess() throws MessageDecodingException, SecurityException,
+ IOException, Pvp2Exception, CredentialsNotAvailableException, XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final String b64AuthnReq = generateSaml2Response(credentialProvider.getMetaDataSigningCredential());
+ httpReq.setMethod("POST");
+ httpReq.addParameter("SAMLRequest", b64AuthnReq);
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNull("RelayState is not null", msg.getRelayState());
+ Assert.assertNotNull("Response is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg.getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ org.springframework.util.Assert.isInstanceOf(PvpSProfileResponse.class, msg, "Inbound message is of wrong type");
+
+ }
+
+ @Test
+ public void encodeRequestSuccess() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException, Pvp2Exception {
+ //build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = null;
+ guiBuilderFactory.setVelocityBuilderConfig(createDummyGuiConfig());
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+
+ bindingImpl.encodeRequest(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+ //validate
+ Assert.assertEquals("http StatusCode", 200, httpResp.getStatus());
+ Assert.assertNotNull("PVP msg is null", httpResp.getContentLength());
+
+ Assert.assertEquals("ContentType", "text/html", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String http = httpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertFalse("http body is empty", http.isEmpty());
+
+ Assert.assertFalse("RelayState parameter", http.contains(HTTP_FORM_RELAYSTATE));
+
+ Assert.assertTrue("SAMLRequest parameter", http.contains(HTTP_FORM_SAMLREQ));
+ final String httpSamlReq = extractParamFromHttpForm(http, HTTP_FORM_SAMLREQ);
+ checkSamlMessageSigned(httpSamlReq);
+
+ }
+
+ @Test
+ public void encodeRequestSuccessEcdsa() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException, Pvp2Exception {
+ //build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = null;
+ guiBuilderFactory.setVelocityBuilderConfig(createDummyGuiConfig());
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+
+ bindingImpl.encodeRequest(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMessageSigningCredential(), pendingReq);
+
+ //validate
+ Assert.assertEquals("http StatusCode", 200, httpResp.getStatus());
+ Assert.assertNotNull("PVP msg is null", httpResp.getContentLength());
+
+ Assert.assertEquals("ContentType", "text/html", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String http = httpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertFalse("http body is empty", http.isEmpty());
+
+ Assert.assertFalse("RelayState parameter", http.contains(HTTP_FORM_RELAYSTATE));
+
+ Assert.assertTrue("SAMLRequest parameter", http.contains(HTTP_FORM_SAMLREQ));
+ final String httpSamlReq = extractParamFromHttpForm(http, HTTP_FORM_SAMLREQ);
+ checkSamlMessageSigned(httpSamlReq);
+
+ }
+
+ @Test
+ public void encodeRequestSuccessWithRelayState() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException, Pvp2Exception {
+
+ //build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = RandomStringUtils.randomAlphabetic(10);
+ guiBuilderFactory.setVelocityBuilderConfig(createDummyGuiConfig());
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+
+ bindingImpl.encodeRequest(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+
+ //validate
+ Assert.assertEquals("http StatusCode", 200, httpResp.getStatus());
+ Assert.assertNotNull("PVP msg is null", httpResp.getContentLength());
+
+ Assert.assertEquals("ContentType", "text/html", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String http = httpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertFalse("http body is empty", http.isEmpty());
+
+ Assert.assertTrue("RelayState parameter", http.contains(HTTP_FORM_RELAYSTATE));
+ final String httpRelayState = extractParamFromHttpForm(http, HTTP_FORM_RELAYSTATE);
+ Assert.assertEquals("Wrong RelayState", relayState, httpRelayState);
+
+ Assert.assertTrue("SAMLRequest parameter", http.contains(HTTP_FORM_SAMLREQ));
+ final String httpSamlReq = extractParamFromHttpForm(http, HTTP_FORM_SAMLREQ);
+ checkSamlMessageSigned(httpSamlReq);
+
+ }
+
+ @Test
+ public void encodeResponseSuccessWithRelayState() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException, Pvp2Exception {
+
+ //build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = RandomStringUtils.randomAlphabetic(10);
+ guiBuilderFactory.setVelocityBuilderConfig(createDummyGuiConfig());
+ final StatusResponseType authnReq = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/Response_without_sig_1.xml"));
+
+ bindingImpl.encodeResponse(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+
+ //validate
+ Assert.assertEquals("http StatusCode", 200, httpResp.getStatus());
+ Assert.assertNotNull("PVP msg is null", httpResp.getContentLength());
+
+ Assert.assertEquals("ContentType", "text/html", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String http = httpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertFalse("http body is empty", http.isEmpty());
+
+ Assert.assertTrue("RelayState parameter", http.contains(HTTP_FORM_RELAYSTATE));
+ final String httpRelayState = extractParamFromHttpForm(http, HTTP_FORM_RELAYSTATE);
+ Assert.assertEquals("Wrong RelayState", relayState, httpRelayState);
+
+ Assert.assertTrue("SAMLRequest parameter", http.contains(HTTP_FORM_SAMLRESP));
+ final String httpSamlReq = extractParamFromHttpForm(http, HTTP_FORM_SAMLRESP);
+ checkSamlMessageSigned(httpSamlReq);
+
+ }
+
+ @Test
+ public void encodeResponseSuccess() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException, Pvp2Exception {
+
+ //build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = null;
+ guiBuilderFactory.setVelocityBuilderConfig(createDummyGuiConfig());
+ final StatusResponseType authnReq = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/Response_without_sig_1.xml"));
+
+ bindingImpl.encodeResponse(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+
+ //validate
+ Assert.assertEquals("http StatusCode", 200, httpResp.getStatus());
+ Assert.assertNotNull("PVP msg is null", httpResp.getContentLength());
+
+ Assert.assertEquals("ContentType", "text/html", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String http = httpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertFalse("http body is empty", http.isEmpty());
+
+ Assert.assertFalse("RelayState parameter", http.contains(HTTP_FORM_RELAYSTATE));
+
+ Assert.assertTrue("SAMLRequest parameter", http.contains(HTTP_FORM_SAMLRESP));
+ final String httpSamlReq = extractParamFromHttpForm(http, HTTP_FORM_SAMLRESP);
+ checkSamlMessageSigned(httpSamlReq);
+
+ }
+
+ private IVelocityGuiBuilderConfiguration createDummyGuiConfig() {
+ return new IVelocityGuiBuilderConfiguration() {
+
+ @Override
+ public Map<String, Object> getViewParameters() {
+ return null;
+ }
+
+ @Override
+ public String getViewName() {
+ return "SAML2 Post-Binding";
+ }
+
+ @Override
+ public String getDefaultContentType() {
+ return null;
+ }
+
+ @Override
+ public InputStream getTemplate(String viewName) {
+ return PostBindingTest.class.getResourceAsStream("/data/pvp_postbinding_template.html");
+ }
+
+ @Override
+ public String getClasspathTemplateDir() {
+ return null;
+
+ }
+ };
+ }
+
+ private void checkSamlMessageSigned(String b64Msg) throws ParserConfigurationException,
+ SAXException, IOException, UnmarshallingException {
+ final Element httpSamlReqElment = DomUtils.parseXmlNonValidating(
+ new ByteArrayInputStream(Base64.getDecoder().decode(b64Msg)));
+
+ final UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
+ final Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(httpSamlReqElment);
+ final SignableSAMLObject msg = (SignableSAMLObject) unmarshaller.unmarshall(httpSamlReqElment);
+ Assert.assertTrue("SAML msg not signed", msg.isSigned());
+
+ }
+
+ private String extractParamFromHttpForm(String http, String httpFormRelaystate) {
+ final int startIndex = http.indexOf(httpFormRelaystate) + httpFormRelaystate.length();
+ final int endIndex = http.indexOf("\"", startIndex);
+ return http.substring(startIndex, endIndex);
+
+ }
+
+ private String generateSaml2AuthnRequest(EaafX509Credential credentials)
+ throws XMLParserException, UnmarshallingException, Pvp2Exception, CredentialsNotAvailableException,
+ UnsupportedEncodingException {
+ final MockHttpServletRequest intHttpReq = new MockHttpServletRequest();
+ final MockHttpServletResponse intHttpResp = new MockHttpServletResponse();
+ guiBuilderFactory.setVelocityBuilderConfig(createDummyGuiConfig());
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+ authnReq.setIssueInstant(DateTime.now());
+
+ bindingImpl.encodeRequest(intHttpReq, intHttpResp, authnReq, "http://testservice.org", null,
+ credentials, pendingReq);
+
+ Assert.assertEquals("http StatusCode", 200, intHttpResp.getStatus());
+ final String http = intHttpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertTrue("SAMLRequest parameter", http.contains(HTTP_FORM_SAMLREQ));
+ return extractParamFromHttpForm(http, HTTP_FORM_SAMLREQ);
+
+ }
+
+ private String generateSaml2Response(EaafX509Credential credentials)
+ throws XMLParserException, UnmarshallingException, Pvp2Exception, CredentialsNotAvailableException,
+ UnsupportedEncodingException {
+ final MockHttpServletRequest intHttpReq = new MockHttpServletRequest();
+ final MockHttpServletResponse intHttpResp = new MockHttpServletResponse();
+ guiBuilderFactory.setVelocityBuilderConfig(createDummyGuiConfig());
+ final StatusResponseType response = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/Response_without_sig_1.xml"));
+ response.setIssueInstant(DateTime.now());
+
+ bindingImpl.encodeResponse(intHttpReq, intHttpResp, response, "http://testservice.org", null,
+ credentials, pendingReq);
+
+ Assert.assertEquals("http StatusCode", 200, intHttpResp.getStatus());
+ final String http = intHttpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertTrue("SAMLRequest parameter", http.contains(HTTP_FORM_SAMLRESP));
+ return extractParamFromHttpForm(http, HTTP_FORM_SAMLRESP);
+
+ }
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/RedirectBindingTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/RedirectBindingTest.java
new file mode 100644
index 00000000..37e4acd1
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/RedirectBindingTest.java
@@ -0,0 +1,854 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.binding;
+
+import java.io.IOException;
+import java.net.URLDecoder;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import at.gv.egiz.eaaf.core.api.IRequest;
+import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl;
+import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory;
+import at.gv.egiz.eaaf.modules.pvp2.PvpConstants;
+import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential;
+import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlMessageValidationException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EaafUriCompare;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+import at.gv.egiz.eaaf.modules.pvp2.test.metadata.MetadataResolverTest;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.joda.time.DateTime;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.messaging.decoder.MessageDecodingException;
+import org.opensaml.messaging.encoder.MessageEncodingException;
+import org.opensaml.saml.saml2.core.RequestAbstractType;
+import org.opensaml.saml.saml2.core.StatusResponseType;
+import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.xml.sax.SAXException;
+
+import net.shibboleth.utilities.java.support.net.URIComparator;
+import net.shibboleth.utilities.java.support.net.URISupport;
+import net.shibboleth.utilities.java.support.xml.XMLParserException;
+import okhttp3.HttpUrl;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({ "/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml" })
+@TestPropertySource(locations = { "/config/config_1.props" })
+public class RedirectBindingTest {
+
+ public static final String HTTP_FORM_RELAYSTATE = "RelayState";
+ public static final String HTTP_FORM_RELAYSTATE_PARAM = HTTP_FORM_RELAYSTATE + "=";
+
+ public static final String HTTP_FORM_SAMLREQ = "SAMLRequest";
+ public static final String HTTP_FORM_SAMLREQ_PARAM = HTTP_FORM_SAMLREQ + "=";
+ public static final String HTTP_FORM_SAMLRESP = "SAMLResponse";
+ public static final String HTTP_FORM_SAMLRESP_PARM = HTTP_FORM_SAMLRESP + "=";
+
+ public static final String HTTP_REDIRECT_SIGALG = "SigAlg";
+ public static final String HTTP_REDIRECT_SIGALG_PARAM = HTTP_REDIRECT_SIGALG + "=";
+ public static final String HTTP_REDIRECT_SIGNATURE = "Signature";
+ public static final String HTTP_REDIRECT_SIGNATURE_PARAM = HTTP_REDIRECT_SIGNATURE + "=";
+
+ @Autowired
+ private RedirectBinding bindingImpl;
+ @Autowired
+ private DummyCredentialProvider credentialProvider;
+ @Autowired
+ private PvpMetadataResolverFactory metadataResolverFactory;
+ @Autowired private IHttpClientFactory httpClientFactory;
+
+ private static MockWebServer mockWebServer;
+ private static HttpUrl mockServerUrl;
+
+ protected MockHttpServletRequest httpReq;
+ protected MockHttpServletResponse httpResp;
+ protected IRequest pendingReq;
+
+ /**
+ * JUnit class initializer.
+ *
+ * @throws Exception In case of an OpenSAML3 initialization error
+ */
+ @BeforeClass
+ public static void classInitializer() throws Exception {
+ EaafOpenSaml3xInitializer.eaafInitialize();
+
+ mockWebServer = new MockWebServer();
+ mockServerUrl = mockWebServer.url("/sp/metadata");
+ }
+
+ /**
+ * Test initializer.
+ *
+ */
+ @Before
+ public void initialize() {
+ httpReq = new MockHttpServletRequest();
+ httpResp = new MockHttpServletResponse();
+
+ pendingReq = new TestRequestImpl();
+
+ }
+
+ @Test
+ public void checkCanHandle() {
+ httpReq.setMethod("POST");
+ Assert.assertFalse("Wrong canHandle result", bindingImpl.handleDecode("Post", httpReq));
+ Assert.assertFalse("Wrong canHandle result", bindingImpl.handleDecode("Redirect", httpReq));
+
+ httpReq.setMethod("GET");
+ Assert.assertFalse("Wrong canHandle result", bindingImpl.handleDecode("Post", httpReq));
+ Assert.assertTrue("Wrong canHandle result", bindingImpl.handleDecode("Redirect", httpReq));
+ }
+
+ @Test
+ public void wrongHttpRequestMethod() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2MetadataException {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("POST");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString("SAMLRequest=nVRNb9swDD13wP6DoXvkr%2FRjQuzCSFAgQDd0TbfDLoVi0642Wcok2kn766c4duABWw%"
+ + "2B%2BSdQj%2BfhIanF7qKXXgrFCq4SENCAeqFwXQlUJ%2BfZ0N7sht%2BnC8lpGO5Y1%2BKIe4XcDFj3nqCw7vSSkMYppboVli"
+ + "tdgGeZsk32%2BZxEN2M5o1LmWxMusBYMu1VIr29RgNmBakcNaFXBw6R0C0Yhtg3BCOBp%2FQxy%2FlcsuFMeO8Qvijvk%2BOps"
+ + "9Aak2FfHWq4Q8c4BtySHO4eomLCEuipyXURjzeVQGYRE7mLWNC22RK0xIFITzWRDPgsun4IrFn1gQ0evryx%2FE%2Bz4o5Oohv"
+ + "R6sczZjId7XgQ%2FVE%2B9Om5rj%2B%2FCjRRSzsoMyUCjwlaTHgq2ruIBaU6jEG61ayrG777RBLp%2BPR6krofyFP2Y68N402"
+ + "5%2BQ4xTi6ccPFxd9mC8Ot15NI9T7umiDpSd1nrUT4kFLkb96mZR6vzTAERKCpoEpCu6OPbTohCRThtc%2FU%2Bs3AIpuH9ygI"
+ + "hwm7cNYzXGspXSKP0I5qUP9Ruz3e2pRm1%2B00i2Fxne77ecCxRuor1l2Dy1Ifz6o%2F6%2Fso%2B78p%2Bb0%2FDz%2BGdI%2"
+ + "F&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&Signature=DOVMqh17xn4wl%2"
+ + "Byvifm4McMsBjKDVf1eqph9ss362ZEbp2nkAIXUzkNWv72I96iNK3r%2BYbAxY9dwZ8Z7jKzCGiJ9Qm34YSfPvzXWl3EVrdI86"
+ + "9U%2BH6HGIMqVew3cVdr4q3Qv9ZBIhdRxbrDu%2F%2BnMjdf8mzbgcQnfjSQiQIYWxOIXZFyxKsyrxJtIam4hoNwUT7mMN6Rjg"
+ + "zvyeS3mARsTJdcI0Vn4ItiprhLgIkD18V9WIdeSZR0gfRaFj8PKdmXCD%2FIa0cKgjhVKoiIZisV4vcthBOeDIqBORL2Ad3Xhc"
+ + "NRQ3%2BcpAf65zHGMBAv1aRy7Bmv0%2B%2BOvCavufykqI2EHtg%3D%3D");
+
+ httpReq.setParameter(HTTP_FORM_SAMLREQ, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLREQ).substring(HTTP_FORM_SAMLREQ_PARAM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+ Assert.fail("Missing signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.95", e.getErrorId());
+
+ }
+ }
+
+ @Test
+ public void wrongRedirectBindingType() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2MetadataException {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("POST");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString("SAMLRequest=nVRNb9swDD13wP6DoXvkr%2FRjQuzCSFAgQDd0TbfDLoVi0642Wcok2kn766c4duABWw%"
+ + "2B%2BSdQj%2BfhIanF7qKXXgrFCq4SENCAeqFwXQlUJ%2BfZ0N7sht%2BnC8lpGO5Y1%2BKIe4XcDFj3nqCw7vSSkMYppboVli"
+ + "tdgGeZsk32%2BZxEN2M5o1LmWxMusBYMu1VIr29RgNmBakcNaFXBw6R0C0Yhtg3BCOBp%2FQxy%2FlcsuFMeO8Qvijvk%2BOps"
+ + "9Aak2FfHWq4Q8c4BtySHO4eomLCEuipyXURjzeVQGYRE7mLWNC22RK0xIFITzWRDPgsun4IrFn1gQ0evryx%2FE%2Bz4o5Oohv"
+ + "R6sczZjId7XgQ%2FVE%2B9Om5rj%2B%2FCjRRSzsoMyUCjwlaTHgq2ruIBaU6jEG61ayrG777RBLp%2BPR6krofyFP2Y68N402"
+ + "5%2BQ4xTi6ccPFxd9mC8Ot15NI9T7umiDpSd1nrUT4kFLkb96mZR6vzTAERKCpoEpCu6OPbTohCRThtc%2FU%2Bs3AIpuH9ygI"
+ + "hwm7cNYzXGspXSKP0I5qUP9Ruz3e2pRm1%2B00i2Fxne77ecCxRuor1l2Dy1Ifz6o%2F6%2Fso%2B78p%2Bb0%2FDz%2BGdI%2"
+ + "F&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&Signature=DOVMqh17xn4wl%2"
+ + "Byvifm4McMsBjKDVf1eqph9ss362ZEbp2nkAIXUzkNWv72I96iNK3r%2BYbAxY9dwZ8Z7jKzCGiJ9Qm34YSfPvzXWl3EVrdI86"
+ + "9U%2BH6HGIMqVew3cVdr4q3Qv9ZBIhdRxbrDu%2F%2BnMjdf8mzbgcQnfjSQiQIYWxOIXZFyxKsyrxJtIam4hoNwUT7mMN6Rjg"
+ + "zvyeS3mARsTJdcI0Vn4ItiprhLgIkD18V9WIdeSZR0gfRaFj8PKdmXCD%2FIa0cKgjhVKoiIZisV4vcthBOeDIqBORL2Ad3Xhc"
+ + "NRQ3%2BcpAf65zHGMBAv1aRy7Bmv0%2B%2BOvCavufykqI2EHtg%3D%3D");
+
+ httpReq.setParameter(HTTP_FORM_SAMLREQ, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLREQ).substring(HTTP_FORM_SAMLREQ_PARAM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+ httpReq.setParameter("SAMLEncoding", RandomStringUtils.randomAlphabetic(5));
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+ Assert.fail("Missing signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.95", e.getErrorId());
+
+ }
+ }
+
+ @Test
+ public void decodeRequestNoSignature() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2MetadataException {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("GET");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString("SAMLRequest=nVRNb9swDD13wP6DoXvkr%2FRjQuzCSFAgQDd0TbfDLoVi0642Wcok2kn766c4duABWw%"
+ + "2B%2BSdQj%2BfhIanF7qKXXgrFCq4SENCAeqFwXQlUJ%2BfZ0N7sht%2BnC8lpGO5Y1%2BKIe4XcDFj3nqCw7vSSkMYppboVli"
+ + "tdgGeZsk32%2BZxEN2M5o1LmWxMusBYMu1VIr29RgNmBakcNaFXBw6R0C0Yhtg3BCOBp%2FQxy%2FlcsuFMeO8Qvijvk%2BOps"
+ + "9Aak2FfHWq4Q8c4BtySHO4eomLCEuipyXURjzeVQGYRE7mLWNC22RK0xIFITzWRDPgsun4IrFn1gQ0evryx%2FE%2Bz4o5Oohv"
+ + "R6sczZjId7XgQ%2FVE%2B9Om5rj%2B%2FCjRRSzsoMyUCjwlaTHgq2ruIBaU6jEG61ayrG777RBLp%2BPR6krofyFP2Y68N402"
+ + "5%2BQ4xTi6ccPFxd9mC8Ot15NI9T7umiDpSd1nrUT4kFLkb96mZR6vzTAERKCpoEpCu6OPbTohCRThtc%2FU%2Bs3AIpuH9ygI"
+ + "hwm7cNYzXGspXSKP0I5qUP9Ruz3e2pRm1%2B00i2Fxne77ecCxRuor1l2Dy1Ifz6o%2F6%2Fso%2B78p%2Bb0%2FDz%2BGdI%2"
+ + "F&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&Signature=DOVMqh17xn4wl%2"
+ + "Byvifm4McMsBjKDVf1eqph9ss362ZEbp2nkAIXUzkNWv72I96iNK3r%2BYbAxY9dwZ8Z7jKzCGiJ9Qm34YSfPvzXWl3EVrdI86"
+ + "9U%2BH6HGIMqVew3cVdr4q3Qv9ZBIhdRxbrDu%2F%2BnMjdf8mzbgcQnfjSQiQIYWxOIXZFyxKsyrxJtIam4hoNwUT7mMN6Rjg"
+ + "zvyeS3mARsTJdcI0Vn4ItiprhLgIkD18V9WIdeSZR0gfRaFj8PKdmXCD%2FIa0cKgjhVKoiIZisV4vcthBOeDIqBORL2Ad3Xhc"
+ + "NRQ3%2BcpAf65zHGMBAv1aRy7Bmv0%2B%2BOvCavufykqI2EHtg%3D%3D");
+
+ httpReq.setParameter(HTTP_FORM_SAMLREQ, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLREQ).substring(HTTP_FORM_SAMLREQ_PARAM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+ Assert.fail("Missing signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.02", e.getErrorId());
+
+ }
+ }
+
+ @Test
+ public void decodeRequestWrongEndpoint() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2Exception {
+ final String serviceUrl = "http://wrongEndPoint.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("GET");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString("SAMLRequest=nVRNb9swDD13wP6DoXvkr%2FRjQuzCSFAgQDd0TbfDLoVi0642Wcok2kn766c4duABWw%"
+ + "2B%2BSdQj%2BfhIanF7qKXXgrFCq4SENCAeqFwXQlUJ%2BfZ0N7sht%2BnC8lpGO5Y1%2BKIe4XcDFj3nqCw7vSSkMYppboVli"
+ + "tdgGeZsk32%2BZxEN2M5o1LmWxMusBYMu1VIr29RgNmBakcNaFXBw6R0C0Yhtg3BCOBp%2FQxy%2FlcsuFMeO8Qvijvk%2BOps"
+ + "9Aak2FfHWq4Q8c4BtySHO4eomLCEuipyXURjzeVQGYRE7mLWNC22RK0xIFITzWRDPgsun4IrFn1gQ0evryx%2FE%2Bz4o5Oohv"
+ + "R6sczZjId7XgQ%2FVE%2B9Om5rj%2B%2FCjRRSzsoMyUCjwlaTHgq2ruIBaU6jEG61ayrG777RBLp%2BPR6krofyFP2Y68N402"
+ + "5%2BQ4xTi6ccPFxd9mC8Ot15NI9T7umiDpSd1nrUT4kFLkb96mZR6vzTAERKCpoEpCu6OPbTohCRThtc%2FU%2Bs3AIpuH9ygI"
+ + "hwm7cNYzXGspXSKP0I5qUP9Ruz3e2pRm1%2B00i2Fxne77ecCxRuor1l2Dy1Ifz6o%2F6%2Fso%2B78p%2Bb0%2FDz%2BGdI%2"
+ + "F&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&Signature=DOVMqh17xn4wl%2"
+ + "Byvifm4McMsBjKDVf1eqph9ss362ZEbp2nkAIXUzkNWv72I96iNK3r%2BYbAxY9dwZ8Z7jKzCGiJ9Qm34YSfPvzXWl3EVrdI86"
+ + "9U%2BH6HGIMqVew3cVdr4q3Qv9ZBIhdRxbrDu%2F%2BnMjdf8mzbgcQnfjSQiQIYWxOIXZFyxKsyrxJtIam4hoNwUT7mMN6Rjg"
+ + "zvyeS3mARsTJdcI0Vn4ItiprhLgIkD18V9WIdeSZR0gfRaFj8PKdmXCD%2FIa0cKgjhVKoiIZisV4vcthBOeDIqBORL2Ad3Xhc"
+ + "NRQ3%2BcpAf65zHGMBAv1aRy7Bmv0%2B%2BOvCavufykqI2EHtg%3D%3D");
+
+ httpReq.setParameter(HTTP_FORM_SAMLREQ, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLREQ).substring(HTTP_FORM_SAMLREQ_PARAM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGNATURE, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGNATURE).substring(HTTP_REDIRECT_SIGNATURE_PARAM.length()),
+ "UTF-8"));
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+ Assert.fail("Wrong signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.10", e.getErrorId());
+ Assert.assertNotNull("Parameters null", e.getParams());
+ Assert.assertEquals("Wrong numer of parameters", 1, e.getParams().length);
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestWrongSignature() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2Exception {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("GET");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString("SAMLRequest=nVRNb9swDD13wP6DoXvkr%2FRjQuzCSFAgQDd0TbfDLoVi0642Wcok2kn766c4duABWw%"
+ + "2B%2BSdQj%2BfhIanF7qKXXgrFCq4SENCAeqFwXQlUJ%2BfZ0N7sht%2BnC8lpGO5Y1%2BKIe4XcDFj3nqCw7vSSkMYppboVli"
+ + "tdgGeZsk32%2BZxEN2M5o1LmWxMusBYMu1VIr29RgNmBakcNaFXBw6R0C0Yhtg3BCOBp%2FQxy%2FlcsuFMeO8Qvijvk%2BOps"
+ + "9Aak2FfHWq4Q8c4BtySHO4eomLCEuipyXURjzeVQGYRE7mLWNC22RK0xIFITzWRDPgsun4IrFn1gQ0evryx%2FE%2Bz4o5Oohv"
+ + "R6sczZjId7XgQ%2FVE%2B9Om5rj%2B%2FCjRRSzsoMyUCjwlaTHgq2ruIBaU6jEG61ayrG777RBLp%2BPR6krofyFP2Y68N402"
+ + "5%2BQ4xTi6ccPFxd9mC8Ot15NI9T7umiDpSd1nrUT4kFLkb96mZR6vzTAERKCpoEpCu6OPbTohCRThtc%2FU%2Bs3AIpuH9ygI"
+ + "hwm7cNYzXGspXSKP0I5qUP9Ruz3e2pRm1%2B00i2Fxne77ecCxRuor1l2Dy1Ifz6o%2F6%2Fso%2B78p%2Bb0%2FDz%2BGdI%2"
+ + "F&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&Signature=DOVMqh17xn4wl%2"
+ + "Byvifm4McMsBjKDVf1eqph9ss362ZEbp2nkAIXUzkNWv72I96iNK3r%2BYbAxY9dwZ8Z7jKzCGiJ9Qm34YSfPvzXWl3EVrdI86"
+ + "9U%2BH6HGIMqVew3cVdr4q3Qv9ZBIhdRxbrDu%2F%2BnMjdf8mzbgcQnfjSQiQIYWxOIXZFyxKsyrxJtIam4hoNwUT7mMN6Rjg"
+ + "zvyeS3mARsTJdcI0Vn4ItiprhLgIkD18V9WIdeSZR0gfRaFj8PKdmXCD%2FIa0cKgjhVKoiIZisV4vcthBOeDIqBORL2Ad3Xhc"
+ + "NRQ3%2BcpAf65zHGMBAv1aRy7Bmv0%2B%2BOvCavufykqI2EHtg%3D%3D");
+
+ httpReq.setParameter(HTTP_FORM_SAMLREQ, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLREQ).substring(HTTP_FORM_SAMLREQ_PARAM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGNATURE, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGNATURE).substring(HTTP_REDIRECT_SIGNATURE_PARAM.length()),
+ "UTF-8"));
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+ Assert.fail("Wrong signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ org.springframework.util.Assert.isInstanceOf(SamlSigningException.class, e, "Wrong Exception type");
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.10", e.getErrorId());
+ Assert.assertNotNull("No error params", e.getParams());
+ Assert.assertEquals("Wrong param size", 1, e.getParams().length);
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestExpired() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2Exception, CredentialsNotAvailableException,
+ XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("GET");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString("SAMLRequest=nVRNb9swDD13wP6DoXvkj2RFJsQujAQFAnTD1nQ97FIoNu1qkyVPop20v36KYwcusPVgQ"
+ + "AeLeiQfH0mvbo6V9FowVmgVk5AGxAOV6VyoMiY%2FHm5nS3KTrCyvZFSztMFndQ9%2FGrDoOUdl2fklJo1RTHMrLFO8AsswY7v"
+ + "0yx2LaMBqo1FnWhIvtRYMulRrrWxTgdmBaUUGW5XD0aV3CEQj9g3CGeFovIU4fhuXXSiOHeNnxJr5PjqbPQOpNiXxtpuYPHGAf"
+ + "cFhnsH1MixgnucZL6JwzhdREYT53MGsbVxoi1xhTKIgCmZBNAsWD8Fn5s6na7qMwp%2FEexwUcvWQXg%2FWOZuxEO%2FrwIfqi"
+ + "XerTcXxffjJIvJZ0UEZKBT4QpJTwdZVnEOlKZTilZYt5djda22Qy6fTp9SlUP7KHzMdeO%2Ba%2FS%2FIcArx5OOHq6s%2BzFe"
+ + "H226mEep9XbTB0pO6zNoZ8U1Lkb14qZT6sDbAEWKCpoEpCtanHlp0QpIpw%2BtfqPUbAHm3D25QEY6T9mGs5jjWWjrF76GY1KF"
+ + "%2BIw6HA7WozW9a6pZC47vd9jOB4hXU9zS9gxakvxjU%2F1f2UXf%2BU3NyeR7%2FGZK%2F&SigAlg=http%3A%2F%2Fwww.w3"
+ + ".org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&Signature=JogFpk2oimCnBCgE7eZx%2B6yoJu2ZCgus5vM1opkTk"
+ + "OLM9qgNMUJJJbIeA3j2TR%2BWx3pUApnV7ed9CuTBF94b3ELkFdaZAetfLzY8gnPLCBmcYIYkwg3bK7ZQWEBJpjNoU%2BaBHXV"
+ + "OgptLUt0qRWavm%2BiPOUXRWpb0PtgvApTieRk32gBfZbuPOltWjrRCKaa2ulKBjB34LqYdAaIWaVix2sGvg128p6lC7bQ%2Fz"
+ + "wmz6j8S5Vn8snvlg48MlBldTWKSZrUERx3MwTyaB17A617XmX2QKo8fGCQ6O7FF4umFyWGAlujI%2FwqafTfPlaNX2usHynHS6"
+ + "XkH5HWCDSAe3%2BVR1w%3D%3D ");
+
+ httpReq.setParameter(HTTP_FORM_SAMLREQ, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLREQ).substring(HTTP_FORM_SAMLREQ_PARAM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGNATURE, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGNATURE).substring(HTTP_REDIRECT_SIGNATURE_PARAM.length()),
+ "UTF-8"));
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+ Assert.fail("Expired message not detected");
+
+ } catch (final Pvp2Exception e) {
+ org.springframework.util.Assert.isInstanceOf(SamlMessageValidationException.class, e,
+ "Wrong Exception type");
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.11", e.getErrorId());
+ Assert.assertNotNull("No error params", e.getParams());
+ Assert.assertEquals("Wrong param size", 1, e.getParams().length);
+
+ }
+
+ }
+
+ @Test
+ public void decodeRequestSuccess() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2Exception, CredentialsNotAvailableException,
+ XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("GET");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString(generateAuthnRequest(credentialProvider.getMetaDataSigningCredential()));
+
+ httpReq.setParameter(HTTP_FORM_SAMLREQ, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLREQ).substring(HTTP_FORM_SAMLREQ_PARAM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGNATURE, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGNATURE).substring(HTTP_REDIRECT_SIGNATURE_PARAM.length()),
+ "UTF-8"));
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNull("RelayState is not null", msg.getRelayState());
+ Assert.assertNotNull("AuthnReq is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg
+ .getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ }
+
+ @Test
+ public void decodeResponseSuccess() throws MessageDecodingException, SecurityException, IOException,
+ Pvp2Exception, CredentialsNotAvailableException, XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ httpReq.setMethod("GET");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setQueryString(generateResponse(credentialProvider.getMetaDataSigningCredential()));
+
+ httpReq.setParameter(HTTP_FORM_SAMLRESP, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLRESP).substring(HTTP_FORM_SAMLRESP_PARM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGNATURE, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGNATURE).substring(HTTP_REDIRECT_SIGNATURE_PARAM.length()),
+ "UTF-8"));
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNull("RelayState is not null", msg.getRelayState());
+ Assert.assertNotNull("Response is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg
+ .getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ }
+
+ @Test
+ public void decodeResponseSuccessWithRelayStateAndMetadataReload() throws MessageDecodingException,
+ SecurityException, IOException, Pvp2Exception, CredentialsNotAvailableException,
+ XMLParserException, UnmarshallingException {
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = RandomStringUtils.randomAlphanumeric(10);
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_wrong_sig.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_junit_keystore.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ null, "jUnit test", httpClientFactory.getHttpClient());
+
+
+ httpReq.setMethod("GET");
+ httpReq.setRequestURI("http://testservice.org");
+ httpReq.setParameter(HTTP_FORM_RELAYSTATE, relayState);
+ httpReq.setQueryString(generateResponse(credentialProvider.getMetaDataSigningCredential()));
+
+ httpReq.setParameter(HTTP_FORM_SAMLRESP, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_FORM_SAMLRESP).substring(HTTP_FORM_SAMLRESP_PARM.length()), "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGALG, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGALG).substring(HTTP_REDIRECT_SIGALG_PARAM.length()),
+ "UTF-8"));
+ httpReq.setParameter(HTTP_REDIRECT_SIGNATURE, URLDecoder.decode(URISupport.getRawQueryStringParameter(
+ httpReq.getQueryString(), HTTP_REDIRECT_SIGNATURE).substring(HTTP_REDIRECT_SIGNATURE_PARAM.length()),
+ "UTF-8"));
+
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
+ comparator);
+
+ Assert.assertNotNull("PVP msg is null", msg);
+ Assert.assertNotNull("RelayState is null", msg.getRelayState());
+ Assert.assertEquals("RelayState not match", relayState, msg.getRelayState());
+ Assert.assertNotNull("Response is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg
+ .getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ }
+
+ @Test
+ public void encodeRequestSuccess() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException,
+ Pvp2Exception {
+ // build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = null;
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ RedirectBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+
+ bindingImpl.encodeRequest(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+ // validate
+ Assert.assertEquals("http StatusCode", 302, httpResp.getStatus());
+ Assert.assertEquals("PVP msg is null", 0, httpResp.getContentLength());
+
+ Assert.assertNull("ContentType", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String locationHeader = httpResp.getHeader("Location");
+ Assert.assertNotNull("Location header is null", locationHeader);
+ Assert.assertFalse("Location header is empty", locationHeader.isEmpty());
+
+ Assert.assertTrue("Wrong redirect URL",
+ locationHeader.startsWith(serviceUrl + "?" + HTTP_FORM_SAMLREQ_PARAM));
+
+ final String respSamlMsg = checkMessagePart(locationHeader, HTTP_FORM_SAMLREQ_PARAM, true);
+ Assert.assertNotNull("Saml msg is null", respSamlMsg);
+ Assert.assertFalse("Saml msg is empty", respSamlMsg.isEmpty());
+
+ final String sigAlg = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGALG_PARAM, true);
+ Assert.assertNotNull("SigAlg is null", sigAlg);
+ Assert.assertFalse("SigAlg is empty", sigAlg.isEmpty());
+ Assert.assertEquals("SigAlg not match", PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ URLDecoder.decode(sigAlg, "UTF-8"));
+
+ final String samlSig = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGNATURE_PARAM, true);
+ Assert.assertNotNull("Saml signature null", samlSig);
+ Assert.assertFalse("Saml signature is empty", samlSig.isEmpty());
+
+ final String respRelayState = checkMessagePart(locationHeader, HTTP_FORM_RELAYSTATE_PARAM, false);
+ Assert.assertNull("RelayState parameter", respRelayState);
+
+ }
+
+ @Test
+ public void encodeRequestSuccessEcdsa() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException,
+ Pvp2Exception {
+ // build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = null;
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ RedirectBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+
+ bindingImpl.encodeRequest(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMessageSigningCredential(), pendingReq);
+
+ // validate
+ // validate
+ Assert.assertEquals("http StatusCode", 302, httpResp.getStatus());
+ Assert.assertEquals("PVP msg is null", 0, httpResp.getContentLength());
+
+ Assert.assertNull("ContentType", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String locationHeader = httpResp.getHeader("Location");
+ Assert.assertNotNull("Location header is null", locationHeader);
+ Assert.assertFalse("Location header is empty", locationHeader.isEmpty());
+
+ Assert.assertTrue("Wrong redirect URL",
+ locationHeader.startsWith(serviceUrl + "?" + HTTP_FORM_SAMLREQ_PARAM));
+
+ final String respSamlMsg = checkMessagePart(locationHeader, HTTP_FORM_SAMLREQ_PARAM, true);
+ Assert.assertNotNull("Saml msg is null", respSamlMsg);
+ Assert.assertFalse("Saml msg is empty", respSamlMsg.isEmpty());
+
+ final String sigAlg = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGALG_PARAM, true);
+ Assert.assertNotNull("SigAlg is null", sigAlg);
+ Assert.assertFalse("SigAlg is empty", sigAlg.isEmpty());
+ Assert.assertEquals("SigAlg not match", PvpConstants.DEFAULT_SIGNING_METHODE_EC,
+ URLDecoder.decode(sigAlg, "UTF-8"));
+
+ final String samlSig = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGNATURE_PARAM, true);
+ Assert.assertNotNull("Saml signature null", samlSig);
+ Assert.assertFalse("Saml signature is empty", samlSig.isEmpty());
+
+ final String respRelayState = checkMessagePart(locationHeader, HTTP_FORM_RELAYSTATE_PARAM, false);
+ Assert.assertNull("RelayState parameter", respRelayState);
+
+ }
+
+ @Test
+ public void encodeRequestSuccessWithRelayState() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException,
+ Pvp2Exception {
+
+ // build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = RandomStringUtils.randomAlphabetic(10);
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ RedirectBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+
+ bindingImpl.encodeRequest(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+ // validate
+ Assert.assertEquals("http StatusCode", 302, httpResp.getStatus());
+ Assert.assertEquals("PVP msg is null", 0, httpResp.getContentLength());
+
+ Assert.assertNull("ContentType", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String locationHeader = httpResp.getHeader("Location");
+ Assert.assertNotNull("Location header is null", locationHeader);
+ Assert.assertFalse("Location header is empty", locationHeader.isEmpty());
+
+ Assert.assertTrue("Wrong redirect URL",
+ locationHeader.startsWith(serviceUrl + "?" + HTTP_FORM_SAMLREQ_PARAM));
+
+ final String respSamlMsg = checkMessagePart(locationHeader, HTTP_FORM_SAMLREQ_PARAM, true);
+ Assert.assertNotNull("Saml msg is null", respSamlMsg);
+ Assert.assertFalse("Saml msg is empty", respSamlMsg.isEmpty());
+
+ final String sigAlg = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGALG_PARAM, true);
+ Assert.assertNotNull("SigAlg is null", sigAlg);
+ Assert.assertFalse("SigAlg is empty", sigAlg.isEmpty());
+ Assert.assertEquals("SigAlg not match", PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ URLDecoder.decode(sigAlg, "UTF-8"));
+
+ final String samlSig = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGNATURE_PARAM, true);
+ Assert.assertNotNull("Saml signature null", samlSig);
+ Assert.assertFalse("Saml signature is empty", samlSig.isEmpty());
+
+ final String respRelayState = checkMessagePart(locationHeader, HTTP_FORM_RELAYSTATE_PARAM, false);
+ Assert.assertNotNull("RelayState parameter", respRelayState);
+ Assert.assertEquals("RelayState not match", relayState,
+ URLDecoder.decode(respRelayState, "UTF-8"));
+
+ }
+
+ @Test
+ public void encodeResponseSuccessWithRelayState() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException,
+ Pvp2Exception {
+
+ // build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = RandomStringUtils.randomAlphabetic(10);
+ final StatusResponseType authnReq = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ RedirectBindingTest.class.getResourceAsStream("/data/Response_without_sig_1.xml"));
+
+ bindingImpl.encodeResponse(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+ // validate
+ Assert.assertEquals("http StatusCode", 302, httpResp.getStatus());
+ Assert.assertEquals("PVP msg is null", 0, httpResp.getContentLength());
+
+ Assert.assertNull("ContentType", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String locationHeader = httpResp.getHeader("Location");
+ Assert.assertNotNull("Location header is null", locationHeader);
+ Assert.assertFalse("Location header is empty", locationHeader.isEmpty());
+
+ Assert.assertTrue("Wrong redirect URL",
+ locationHeader.startsWith(serviceUrl + "?" + HTTP_FORM_SAMLRESP_PARM));
+
+ final String respSamlMsg = checkMessagePart(locationHeader, HTTP_FORM_SAMLRESP_PARM, true);
+ Assert.assertNotNull("Saml msg is null", respSamlMsg);
+ Assert.assertFalse("Saml msg is empty", respSamlMsg.isEmpty());
+
+ final String sigAlg = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGALG_PARAM, true);
+ Assert.assertNotNull("SigAlg is null", sigAlg);
+ Assert.assertFalse("SigAlg is empty", sigAlg.isEmpty());
+ Assert.assertEquals("SigAlg not match", PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ URLDecoder.decode(sigAlg, "UTF-8"));
+
+ final String samlSig = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGNATURE_PARAM, true);
+ Assert.assertNotNull("Saml signature null", samlSig);
+ Assert.assertFalse("Saml signature is empty", samlSig.isEmpty());
+
+ final String respRelayState = checkMessagePart(locationHeader, HTTP_FORM_RELAYSTATE_PARAM, false);
+ Assert.assertNotNull("RelayState parameter", respRelayState);
+ Assert.assertEquals("RelayState not match", relayState,
+ URLDecoder.decode(respRelayState, "UTF-8"));
+
+ }
+
+ @Test
+ public void encodeResponseSuccess() throws MessageDecodingException, SecurityException,
+ MessageEncodingException, XMLParserException, UnmarshallingException,
+ CredentialsNotAvailableException, ParserConfigurationException, SAXException, IOException,
+ Pvp2Exception {
+
+ // build test data
+ final String serviceUrl = "http://testservice.org";
+ final String relayState = null;
+ final StatusResponseType authnReq = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ RedirectBindingTest.class.getResourceAsStream("/data/Response_without_sig_1.xml"));
+
+ bindingImpl.encodeResponse(httpReq, httpResp, authnReq, serviceUrl, relayState,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+ // validate
+ Assert.assertEquals("http StatusCode", 302, httpResp.getStatus());
+ Assert.assertEquals("PVP msg is null", 0, httpResp.getContentLength());
+
+ Assert.assertNull("ContentType", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String locationHeader = httpResp.getHeader("Location");
+ Assert.assertNotNull("Location header is null", locationHeader);
+ Assert.assertFalse("Location header is empty", locationHeader.isEmpty());
+
+ Assert.assertTrue("Wrong redirect URL",
+ locationHeader.startsWith(serviceUrl + "?" + HTTP_FORM_SAMLRESP_PARM));
+
+ final String respSamlMsg = checkMessagePart(locationHeader, HTTP_FORM_SAMLRESP_PARM, true);
+ Assert.assertNotNull("Saml msg is null", respSamlMsg);
+ Assert.assertFalse("Saml msg is empty", respSamlMsg.isEmpty());
+
+ final String sigAlg = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGALG_PARAM, true);
+ Assert.assertNotNull("SigAlg is null", sigAlg);
+ Assert.assertFalse("SigAlg is empty", sigAlg.isEmpty());
+ Assert.assertEquals("SigAlg not match", PvpConstants.DEFAULT_SIGNING_METHODE_RSA,
+ URLDecoder.decode(sigAlg, "UTF-8"));
+
+ final String samlSig = checkMessagePart(locationHeader, HTTP_REDIRECT_SIGNATURE_PARAM, true);
+ Assert.assertNotNull("Saml signature null", samlSig);
+ Assert.assertFalse("Saml signature is empty", samlSig.isEmpty());
+
+ final String respRelayState = checkMessagePart(locationHeader, HTTP_FORM_RELAYSTATE_PARAM, false);
+ Assert.assertNull("RelayState parameter", respRelayState);
+
+ }
+
+ private String checkMessagePart(String locationHeader, String httpFormSamlreq, boolean isRequired) {
+ final int startIndex = locationHeader.indexOf(httpFormSamlreq);
+ int endIndex = locationHeader.indexOf("&", startIndex);
+
+ if (isRequired && startIndex == -1) {
+ Assert.fail("Element: " + httpFormSamlreq + " NOT found");
+
+ } else if (startIndex == -1) {
+ return null;
+
+ }
+
+ if (endIndex == -1) {
+ endIndex = locationHeader.length();
+
+ }
+
+ return locationHeader.substring(startIndex + httpFormSamlreq.length(), endIndex);
+
+ }
+
+ private String generateAuthnRequest(EaafX509Credential credential) throws Pvp2Exception,
+ XMLParserException, UnmarshallingException {
+ final MockHttpServletRequest intHttpReq = new MockHttpServletRequest();
+ final MockHttpServletResponse intHttpResp = new MockHttpServletResponse();
+
+ final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ RedirectBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+ authnReq.setIssueInstant(DateTime.now());
+
+ bindingImpl.encodeRequest(intHttpReq, intHttpResp, authnReq, "http://testservice.org", null,
+ credential, pendingReq);
+
+ Assert.assertEquals("http StatusCode", 302, intHttpResp.getStatus());
+ final String locationHeader = intHttpResp.getHeader("Location");
+ Assert.assertNotNull("Location header is null", locationHeader);
+ return locationHeader.split("\\?")[1];
+
+ }
+
+ private String generateResponse(EaafX509Credential credential) throws Pvp2Exception,
+ XMLParserException, UnmarshallingException {
+ new MockHttpServletRequest();
+ final MockHttpServletRequest intHttpReq = new MockHttpServletRequest();
+ final MockHttpServletResponse intHttpResp = new MockHttpServletResponse();
+
+ final StatusResponseType authnReq = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ RedirectBindingTest.class.getResourceAsStream("/data/Response_without_sig_1.xml"));
+ authnReq.setIssueInstant(DateTime.now());
+
+ bindingImpl.encodeResponse(intHttpReq, intHttpResp, authnReq, "http://testservice.org", null,
+ credential, pendingReq);
+
+ Assert.assertEquals("http StatusCode", 302, intHttpResp.getStatus());
+ final String locationHeader = intHttpResp.getHeader("Location");
+ Assert.assertNotNull("Location header is null", locationHeader);
+ return locationHeader.split("\\?")[1];
+
+ }
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/SoapBindingTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/SoapBindingTest.java
new file mode 100644
index 00000000..f3a7e01d
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/binding/SoapBindingTest.java
@@ -0,0 +1,216 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.binding;
+
+import java.io.ByteArrayOutputStream;
+import java.io.UnsupportedEncodingException;
+
+import at.gv.egiz.eaaf.core.api.IRequest;
+import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl;
+import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception;
+import at.gv.egiz.eaaf.modules.pvp2.impl.binding.SoapBinding;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer;
+import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EaafUriCompare;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+
+import org.joda.time.DateTime;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
+import org.opensaml.core.xml.io.Marshaller;
+import org.opensaml.core.xml.io.MarshallingException;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.saml.saml2.core.RequestAbstractType;
+import org.opensaml.saml.saml2.core.StatusResponseType;
+import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
+import org.opensaml.soap.soap11.Envelope;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import net.shibboleth.utilities.java.support.logic.Constraint;
+import net.shibboleth.utilities.java.support.net.URIComparator;
+import net.shibboleth.utilities.java.support.xml.SerializeSupport;
+import net.shibboleth.utilities.java.support.xml.XMLParserException;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml"})
+@TestPropertySource(locations = {"/config/config_1.props"})
+public class SoapBindingTest {
+
+ @Autowired private SoapBinding bindingImpl;
+ @Autowired private PvpMetadataResolverFactory metadataResolverFactory;
+ @Autowired private DummyCredentialProvider credentialProvider;
+
+ protected MockHttpServletRequest httpReq;
+ protected MockHttpServletResponse httpResp;
+ protected IRequest pendingReq;
+
+ /**
+ * JUnit class initializer.
+ *
+ * @throws Exception In case of an OpenSAML3 initialization error
+ */
+ @BeforeClass
+ public static void classInitializer() throws Exception {
+ EaafOpenSaml3xInitializer.eaafInitialize();
+
+ }
+
+ /**
+ * Test initializer.
+ *
+ */
+ @Before
+ public void initialize() {
+ httpReq = new MockHttpServletRequest();
+ httpResp = new MockHttpServletResponse();
+
+ pendingReq = new TestRequestImpl();
+
+ }
+
+ @Test
+ public void withoutSig() throws Pvp2Exception, MarshallingException, XMLParserException, UnmarshallingException {
+ final String serviceUrl = "https://localhost/pvp2/post";
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final RequestAbstractType payload = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_without_sig_1.xml"));
+ payload.setIssueInstant(DateTime.now());
+ final Envelope enveloped = Saml2Utils.buildSoap11Envelope(payload);
+ final Marshaller marshaller = Constraint.isNotNull(
+ XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(enveloped),
+ "SOAP Envelope marshaller not available");
+ final ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
+ SerializeSupport.writeNode(marshaller.marshall(enveloped), arrayOut);
+ httpReq.setMethod("POST");
+ httpReq.setContentType("text/xml");
+ httpReq.setContent(arrayOut.toByteArray());
+
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider,
+ SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+ Assert.fail("Missing signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.02", e.getErrorId());
+
+ }
+ }
+
+ @Test
+ public void wrongSignature() throws Pvp2Exception, MarshallingException, XMLParserException, UnmarshallingException {
+ final String serviceUrl = "https://localhost/pvp2/post";
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final RequestAbstractType payload = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_with_sig_1.xml"));
+ payload.setIssueInstant(DateTime.now());
+ final Envelope enveloped = Saml2Utils.buildSoap11Envelope(payload);
+ final Marshaller marshaller = Constraint.isNotNull(
+ XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(enveloped),
+ "SOAP Envelope marshaller not available");
+ final ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
+ SerializeSupport.writeNode(marshaller.marshall(enveloped), arrayOut);
+ httpReq.setMethod("POST");
+ httpReq.setContentType("text/xml");
+ httpReq.setContent(arrayOut.toByteArray());
+
+
+ try {
+ bindingImpl.decode(httpReq, httpResp, metadataProvider,
+ SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+ Assert.fail("Missing signature not detected");
+
+ } catch (final Pvp2Exception e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.10", e.getErrorId());
+
+ }
+ }
+
+ @Test
+ public void validSignature() throws Pvp2Exception, MarshallingException, XMLParserException,
+ UnmarshallingException, CredentialsNotAvailableException {
+ final String serviceUrl = "https://localhost/pvp2/post";
+ final IPvp2MetadataProvider metadataProvider =
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit metadata resolver", null);
+ final URIComparator comparator = new EaafUriCompare(serviceUrl);
+
+ final RequestAbstractType payload = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/AuthRequest_with_sig_1.xml"));
+ payload.setIssueInstant(DateTime.now());
+ final RequestAbstractType signedPayload = Saml2Utils.signSamlObject(
+ payload, credentialProvider.getMetaDataSigningCredential(), true);
+
+ final Envelope enveloped = Saml2Utils.buildSoap11Envelope(signedPayload);
+ final Marshaller marshaller = Constraint.isNotNull(
+ XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(enveloped),
+ "SOAP Envelope marshaller not available");
+ final ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
+ SerializeSupport.writeNode(marshaller.marshall(enveloped), arrayOut);
+ httpReq.setMethod("POST");
+ httpReq.setContentType("text/xml");
+ httpReq.setContent(arrayOut.toByteArray());
+
+
+ final InboundMessageInterface msg =
+ bindingImpl.decode(httpReq, httpResp, metadataProvider,
+ SPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator);
+
+ Assert.assertNotNull("Inbound msg is null", msg);
+ Assert.assertNotNull("AuthnReq is null", msg.getInboundMessage());
+ Assert.assertNotNull("EntityId is null", msg.getEntityID());
+ Assert.assertEquals("EntityId not match", "https://demo.egiz.gv.at/demoportal_demologin/", msg.getEntityID());
+ Assert.assertTrue("Wrong isVerified flag", msg.isVerified());
+
+ }
+
+ @Test
+ public void encodeResponse() throws XMLParserException, UnmarshallingException,
+ Pvp2Exception, CredentialsNotAvailableException, UnsupportedEncodingException {
+ final String serviceUrl = "http://testservice.org";
+
+ final StatusResponseType response = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ PostBindingTest.class.getResourceAsStream("/data/Response_without_sig_1.xml"));
+
+ bindingImpl.encodeResponse(httpReq, httpResp, response, serviceUrl, null,
+ credentialProvider.getMetaDataSigningCredential(), pendingReq);
+
+ Assert.assertEquals("http StatusCode", 200, httpResp.getStatus());
+ Assert.assertNotNull("PVP msg is null", httpResp.getContentLength());
+
+ Assert.assertEquals("ContentType", "text/xml", httpResp.getContentType());
+ Assert.assertEquals("Encoding", "UTF-8", httpResp.getCharacterEncoding());
+
+ final String http = httpResp.getContentAsString();
+ Assert.assertNotNull("http body is null", http);
+ Assert.assertFalse("http body is empty", http.isEmpty());
+
+ }
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java
new file mode 100644
index 00000000..7418e1b3
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java
@@ -0,0 +1,93 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.dummy;
+
+import at.gv.egiz.eaaf.core.api.idp.IConfiguration;
+import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException;
+import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration;
+import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType;
+import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
+public class DummyCredentialProvider extends AbstractCredentialProvider {
+
+ @Autowired IConfiguration basicConfig;
+
+ public static final String KEYSTORE_TYPE = "keystore.type";
+ public static final String KEYSTORE_PATH = "keystore.path";
+ public static final String KEYSTORE_PASSWORD = "keystore.pass";
+ public static final String KEYSTORE_NAME = "keystore.name";
+
+
+ public static final String KEY_METADATA_ALIAS = "key.metadata.alias";
+ public static final String KEY_METADATA_PASSWORD = "key.metadata.pass";
+
+ public static final String KEY_SIGNING_ALIAS = "key.sig.alias";
+ public static final String KEY_SIGNING_PASSWORD = "key.sig.pass";
+
+ public static final String KEY_ENCRYPTION_ALIAS = "key.enc.alias";
+ public static final String KEY_ENCRYPTION_PASSWORD = "key.enc.pass";
+
+ private static final String KEYSTORENAME = "jUnit test credential provider";
+
+ @Override
+ public KeyStoreConfiguration getBasicKeyStoreConfig() throws EaafConfigurationException {
+ final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration();
+ keyStoreConfig.setFriendlyName(KEYSTORENAME);
+ keyStoreConfig.setKeyStoreType(getKeyStoreType());
+
+ keyStoreConfig.setKeyStoreName(
+ basicConfig.getBasicConfiguration(KEYSTORE_NAME));
+
+ keyStoreConfig.setSoftKeyStoreFilePath(getKeyStoreFilePath());
+ keyStoreConfig.setSoftKeyStorePassword(getKeyStorePassword());
+
+ return keyStoreConfig;
+ }
+
+ public String getKeyStoreType() {
+ return basicConfig.getBasicConfiguration(KEYSTORE_TYPE, KeyStoreType.JKS.getKeyStoreType());
+
+ }
+
+ public String getKeyStoreFilePath() {
+ final String path = basicConfig.getBasicConfiguration(KEYSTORE_PATH);
+ return path;
+
+ }
+
+ public String getKeyStorePassword() {
+ return basicConfig.getBasicConfiguration(KEYSTORE_PASSWORD);
+ }
+
+ @Override
+ public String getMetadataKeyAlias() {
+ return basicConfig.getBasicConfiguration(KEY_METADATA_ALIAS);
+ }
+
+ @Override
+ public String getMetadataKeyPassword() {
+ return basicConfig.getBasicConfiguration(KEY_METADATA_PASSWORD);
+ }
+
+ @Override
+ public String getSignatureKeyAlias() {
+ return basicConfig.getBasicConfiguration(KEY_SIGNING_ALIAS);
+ }
+
+ @Override
+ public String getSignatureKeyPassword() {
+ return basicConfig.getBasicConfiguration(KEY_SIGNING_PASSWORD);
+ }
+
+ @Override
+ public String getEncryptionKeyAlias() {
+ return basicConfig.getBasicConfiguration(KEY_ENCRYPTION_ALIAS);
+ }
+
+ @Override
+ public String getEncryptionKeyPassword() {
+ return basicConfig.getBasicConfiguration(KEY_ENCRYPTION_PASSWORD);
+ }
+
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyMetadataProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyMetadataProvider.java
new file mode 100644
index 00000000..64ebe00c
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyMetadataProvider.java
@@ -0,0 +1,80 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.dummy;
+
+import java.io.IOException;
+import java.security.cert.CertificateException;
+import java.util.ArrayList;
+import java.util.List;
+
+import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException;
+import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.AbstractChainingMetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory;
+
+import org.opensaml.saml.metadata.resolver.MetadataResolver;
+import org.opensaml.saml.metadata.resolver.filter.MetadataFilter;
+import org.opensaml.saml.metadata.resolver.filter.MetadataFilterChain;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public class DummyMetadataProvider extends AbstractChainingMetadataProvider {
+
+ private final List<String> configuredMetadataUrls = new ArrayList<>();
+ private String metadataProviderName;
+
+ @Autowired PvpMetadataResolverFactory resolverFactory;
+ @Autowired IHttpClientFactory httpClientFactory;
+ private final MetadataFilterChain metadataFilters = new MetadataFilterChain();
+
+ @Override
+ protected String getMetadataUrl(String entityId) throws EaafConfigurationException {
+ return entityId;
+
+ }
+
+ @Override
+ protected MetadataResolver createNewMetadataProvider(String entityId) throws EaafConfigurationException,
+ IOException, CertificateException {
+ try {
+ return resolverFactory.createMetadataProvider(entityId, metadataFilters, entityId, null,
+ httpClientFactory.getHttpClient());
+
+ } catch (final Pvp2MetadataException e) {
+ throw new EaafConfigurationException("internal.pvp.04", new Object[] {entityId}, e);
+
+ }
+
+ }
+
+ @Override
+ protected List<String> getAllMetadataUrlsFromConfiguration() throws EaafConfigurationException {
+ return configuredMetadataUrls;
+
+ }
+
+ @Override
+ protected String getMetadataProviderId() {
+ return metadataProviderName;
+
+ }
+
+ public void addMetadataUrls(List<String> metadataUrls) {
+ configuredMetadataUrls.addAll(metadataUrls);
+
+ }
+
+ public void clearMetadataUrls() {
+ configuredMetadataUrls.clear();
+
+ }
+
+ public void setMetadataProviderName(String name) {
+ metadataProviderName = name;
+
+ }
+
+ public void setMetadataFilters(List<MetadataFilter> filtersToUse) {
+ metadataFilters.setFilters(filtersToUse);
+
+ }
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/ChainingMetadataTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/ChainingMetadataTest.java
new file mode 100644
index 00000000..6abe52dc
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/ChainingMetadataTest.java
@@ -0,0 +1,167 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.metadata;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+
+import at.gv.egiz.eaaf.core.api.idp.IConfiguration;
+import at.gv.egiz.eaaf.core.impl.utils.FileUtils;
+import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyMetadataProvider;
+
+import org.apache.commons.io.IOUtils;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.core.criterion.EntityIdCriterion;
+import org.opensaml.saml.criterion.EntityRoleCriterion;
+import org.opensaml.saml.saml2.metadata.EntityDescriptor;
+import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
+import net.shibboleth.utilities.java.support.resolver.ResolverException;
+import okhttp3.HttpUrl;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({ "/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml" })
+@TestPropertySource(locations = { "/config/config_1.props" })
+public class ChainingMetadataTest {
+
+ private static MockWebServer mockWebServer;
+ private static HttpUrl mockServerUrl;
+
+ @Autowired DummyMetadataProvider metadataProvider;
+ @Autowired PvpMetadataResolverFactory factory;
+ @Autowired IConfiguration authConfig;
+ @Autowired IHttpClientFactory httpFactory;
+
+
+ /**
+ * JUnit class initializer.
+ *
+ * @throws Exception In case of an OpenSAML3 initialization error
+ */
+ @BeforeClass
+ public static void classInitializer() throws Exception {
+ EaafOpenSaml3xInitializer.eaafInitialize();
+
+ mockWebServer = new MockWebServer();
+ mockServerUrl = mockWebServer.url("/sp/metadata");
+ }
+
+ @Test
+ public void runGarbageCollector() throws ResolverException, Pvp2MetadataException,
+ UnsupportedEncodingException, IOException {
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_moaid_test.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final EntityDescriptor entityDesc =
+ metadataProvider.getEntityDescriptor("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml");
+ Assert.assertNotNull("EntityDesc is null", entityDesc);
+
+ final IPvp2MetadataProvider provider2 = factory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_junit_keystore.xml", null, "jUnit", null);
+ metadataProvider.addMetadataResolverIntoChain(provider2);
+
+ final IPvp2MetadataProvider provider3 = factory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_valid_with_entityCategory_egov.xml", null, "jUnit", null);
+ metadataProvider.addMetadataResolverIntoChain(provider3);
+
+ final IPvp2MetadataProvider provider4 = factory.createMetadataProvider(
+ mockServerUrl.url().toString(), null, "jUnit", httpFactory.getHttpClient());
+ metadataProvider.addMetadataResolverIntoChain(provider4);
+
+
+
+
+ metadataProvider.addMetadataUrls(Arrays.asList(
+ FileUtils.makeAbsoluteUrl("classpath:/data/pvp_metadata_junit_keystore.xml",
+ authConfig.getConfigurationRootDirectory()), mockServerUrl.url().toString()));
+
+ metadataProvider.runGarbageCollector();
+
+ final EntityDescriptor entityDesc4 =
+ metadataProvider.getEntityDescriptor("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml");
+ Assert.assertNotNull("EntityDesc is null", entityDesc4);
+
+
+ metadataProvider.clearMetadataUrls();
+ metadataProvider.runGarbageCollector();
+
+ final CriteriaSet criteria = new CriteriaSet();
+ criteria.add(new EntityIdCriterion("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml"));
+ final EntityDescriptor entityDesc5 = metadataProvider.resolveSingle(criteria);
+ Assert.assertNotNull("EntityDesc is null", entityDesc5);
+
+
+ final CriteriaSet criteria6 = new CriteriaSet();
+ criteria6.add(new EntityIdCriterion("classpath:/data/classpath:/data/pvp_metadata_junit_keystore.xml"));
+ final EntityDescriptor entityDesc6 = metadataProvider.resolveSingle(criteria6);
+ Assert.assertNull("EntityDesc not null", entityDesc6);
+
+ metadataProvider.refreshMetadataProvider("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml");
+
+ metadataProvider.clear();
+
+ metadataProvider.refreshMetadataProvider("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml");
+
+ metadataProvider.clear("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml");
+
+ Assert.assertFalse("Wrong refresh flag", metadataProvider.wasLastRefreshSuccess());
+
+ metadataProvider.getMetadataFilter();
+
+ metadataProvider.fullyDestroy();
+
+ metadataProvider.refreshMetadataProvider("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml");
+
+ final CriteriaSet criteria7 = new CriteriaSet();
+ criteria7.add(new EntityIdCriterion("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml"));
+ final Iterable<EntityDescriptor> entityDesc7 = metadataProvider.resolve(criteria7);
+ Assert.assertNotNull("EntityDesc is null", entityDesc7);
+ Assert.assertTrue("is Empty", entityDesc7.iterator().hasNext());
+
+ final CriteriaSet criteria8 = new CriteriaSet();
+ criteria8.add(new EntityIdCriterion("classpath:/data/classpath:/data/pvp_metadata_junit_keystore.xml"));
+ final Iterable<EntityDescriptor> entityDesc8 = metadataProvider.resolve(criteria8);
+ Assert.assertNotNull("EntityDesc not null", entityDesc8);
+ Assert.assertFalse("is not Empty", entityDesc8.iterator().hasNext());
+
+ metadataProvider.refresh();
+
+ metadataProvider.getLastRefresh();
+
+ metadataProvider.getLastSuccessfulRefresh();
+
+ metadataProvider.getLastUpdate();
+
+ metadataProvider.refreshMetadataProvider("classpath:/data/pvp_metadata_junit_keystore_classpath_entityId.xml");
+
+
+ final CriteriaSet criteria9 = new CriteriaSet();
+ criteria9.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
+ final Iterable<EntityDescriptor> entityDesc9 = metadataProvider.resolve(criteria9);
+ Assert.assertNotNull("EntityDesc not null", entityDesc9);
+
+ }
+
+
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataBuilderTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataBuilderTest.java
new file mode 100644
index 00000000..0f8817a0
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataBuilderTest.java
@@ -0,0 +1,301 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.metadata;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+
+import at.gv.egiz.eaaf.core.exceptions.EaafException;
+import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataBuilderConfiguration;
+import at.gv.egiz.eaaf.modules.pvp2.api.utils.IPvp2CredentialProvider;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PvpMetadataBuilder;
+import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
+import org.opensaml.core.xml.io.MarshallingException;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.saml.common.xml.SAMLConstants;
+import org.opensaml.saml.saml2.core.Attribute;
+import org.opensaml.saml.saml2.core.NameIDType;
+import org.opensaml.saml.saml2.metadata.ContactPerson;
+import org.opensaml.saml.saml2.metadata.EntityDescriptor;
+import org.opensaml.saml.saml2.metadata.Organization;
+import org.opensaml.saml.saml2.metadata.RequestedAttribute;
+import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator;
+import org.opensaml.security.SecurityException;
+import org.opensaml.security.credential.Credential;
+import org.opensaml.security.x509.BasicX509Credential;
+import org.opensaml.xmlsec.signature.support.SignatureException;
+import org.opensaml.xmlsec.signature.support.SignatureValidator;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import net.shibboleth.utilities.java.support.xml.XMLParserException;
+
+
+
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({ "/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml" })
+@TestPropertySource(locations = { "/config/config_1.props" })
+public class MetadataBuilderTest {
+
+ @Autowired private PvpMetadataBuilder metadataBuilder;
+ @Autowired private DummyCredentialProvider credentialProvider;
+
+ private static CertificateFactory fact;
+
+ /**
+ * JUnit class initializer.
+ *
+ * @throws Exception In case of an OpenSAML3 initialization error
+ */
+ @BeforeClass
+ public static void classInitializer() throws Exception {
+ EaafOpenSaml3xInitializer.eaafInitialize();
+
+ fact = CertificateFactory.getInstance("X.509");
+ }
+
+ @Test
+ public void buildIdpMetadata() throws CredentialsNotAvailableException, EaafException,
+ SecurityException, TransformerFactoryConfigurationError, MarshallingException,
+ TransformerException, ParserConfigurationException, IOException, SignatureException,
+ XMLParserException, UnmarshallingException, CertificateException {
+
+ final IPvpMetadataBuilderConfiguration config = idpMetadataConfig(credentialProvider, false, true);
+
+ //generate metadata
+ final String metadata = metadataBuilder.buildPvpMetadata(config);
+
+ //validate
+ final EntityDescriptor entity = validateMetadata(metadata);
+ Assert.assertNotNull("IDPSSODescr. is null", entity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
+ Assert.assertNull("IDPSSODescr. is null", entity.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
+
+ }
+
+ @Test
+ public void buildSpMetadata() throws CredentialsNotAvailableException, EaafException,
+ SecurityException, TransformerFactoryConfigurationError, MarshallingException,
+ TransformerException, ParserConfigurationException, IOException, SignatureException,
+ XMLParserException, UnmarshallingException, CertificateException {
+
+ final IPvpMetadataBuilderConfiguration config = idpMetadataConfig(credentialProvider, true, false);
+
+ //generate metadata
+ final String metadata = metadataBuilder.buildPvpMetadata(config);
+
+ //validate
+ final EntityDescriptor entity = validateMetadata(metadata);
+ Assert.assertNull("IDPSSODescr. is null", entity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
+ Assert.assertNotNull("IDPSSODescr. is null", entity.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
+
+ }
+
+ @Test
+ public void buildSpAndIdpMetadata() throws CredentialsNotAvailableException, EaafException,
+ SecurityException, TransformerFactoryConfigurationError, MarshallingException,
+ TransformerException, ParserConfigurationException, IOException, SignatureException,
+ XMLParserException, UnmarshallingException, CertificateException {
+
+ final IPvpMetadataBuilderConfiguration config = idpMetadataConfig(credentialProvider, true, true);
+
+ //generate metadata
+ final String metadata = metadataBuilder.buildPvpMetadata(config);
+
+ //validate
+ final EntityDescriptor entity = validateMetadata(metadata);
+ Assert.assertNotNull("IDPSSODescr. is null", entity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
+ Assert.assertNotNull("IDPSSODescr. is null", entity.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
+
+ }
+
+ private EntityDescriptor validateMetadata(String metadata) throws UnsupportedEncodingException,
+ XMLParserException, UnmarshallingException, SignatureException, CertificateException {
+ Assert.assertNotNull("Metadata is null", metadata);
+ Assert.assertFalse("Metadata is empty", metadata.isEmpty());
+
+ final EntityDescriptor entity = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ new ByteArrayInputStream(metadata.getBytes("UTF-8")));
+
+ Assert.assertNotNull("Unmarshalling failed", entity);
+ Assert.assertNotNull("EntityId is null", entity.getEntityID());
+
+ Assert.assertNotNull("Signature is null", entity.getSignature());
+ final SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator();
+ sigValidator.validate(entity.getSignature());
+
+ final Credential cred = new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/junit_metadata_sig_cert.crt")));
+ SignatureValidator.validate(entity.getSignature(), cred);
+
+ return entity;
+ }
+
+ public static IPvpMetadataBuilderConfiguration idpMetadataConfig(IPvp2CredentialProvider credentialProvider, boolean buildSpInfos, boolean buildIdpInfos) {
+ return new IPvpMetadataBuilderConfiguration() {
+
+ @Override
+ public boolean wantAuthnRequestSigned() {
+ return true;
+ }
+
+ @Override
+ public boolean wantAssertionSigned() {
+ return true;
+ }
+
+ @Override
+ public String getSpSloSoapBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+
+ }
+
+ @Override
+ public String getSpSloRedirectBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+
+ }
+
+ @Override
+ public String getSpSloPostBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public Collection<RequestedAttribute> getSpRequiredAttributes() {
+ return null;
+ }
+
+ @Override
+ public String getSpNameForLogging() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public String getSpAssertionConsumerServiceRedirectBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public String getSpAssertionConsumerServicePostBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public List<String> getSpAllowedNameIdTypes() {
+ return Arrays.asList(NameIDType.PERSISTENT);
+ }
+
+ @Override
+ public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException {
+ return credentialProvider.getMessageSigningCredential();
+ }
+
+ @Override
+ public Organization getOrgansiationInformation() {
+ return null;
+ }
+
+ @Override
+ public int getMetadataValidUntil() {
+ return 10;
+ }
+
+ @Override
+ public EaafX509Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException {
+ return credentialProvider.getMetaDataSigningCredential();
+ }
+
+ @Override
+ public String getIdpWebSsoRedirectBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public String getIdpWebSsoPostBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public String getIdpSloRedirectBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public String getIdpSloPostBindingUrl() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public List<String> getIdpPossibleNameIdTypes() {
+ return Arrays.asList(NameIDType.PERSISTENT);
+ }
+
+ @Override
+ public List<Attribute> getIdpPossibleAttributes() {
+ return null;
+ }
+
+ @Override
+ public String getEntityID() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public String getEntityFriendlyName() {
+ return RandomStringUtils.randomAlphabetic(10);
+ }
+
+ @Override
+ public Credential getEncryptionCredentials() throws CredentialsNotAvailableException {
+ return credentialProvider.getMessageSigningCredential();
+ }
+
+ @Override
+ public List<ContactPerson> getContactPersonInformation() {
+ return null;
+ }
+
+ @Override
+ public boolean buildSpSsoDescriptor() {
+ return buildSpInfos;
+ }
+
+ @Override
+ public boolean buildIdpSsoDescriptor() {
+ return buildIdpInfos;
+ }
+
+ @Override
+ public boolean buildEntitiesDescriptorAsRootElement() {
+ return false;
+ }
+ };
+ }
+}
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataResolverTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataResolverTest.java
new file mode 100644
index 00000000..accdd8b0
--- /dev/null
+++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/metadata/MetadataResolverTest.java
@@ -0,0 +1,742 @@
+package at.gv.egiz.eaaf.modules.pvp2.test.metadata;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.transform.TransformerException;
+
+import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory;
+import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider;
+import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2InternalErrorException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException;
+import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException;
+import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer;
+import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.PvpEntityCategoryFilter;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.SchemaValidationFilter;
+import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.SimpleMetadataSignatureVerificationFilter;
+import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.joda.time.DateTime;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opensaml.core.config.ConfigurationService;
+import org.opensaml.core.criterion.EntityIdCriterion;
+import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
+import org.opensaml.core.xml.io.MarshallingException;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.saml.common.xml.SAMLConstants;
+import org.opensaml.saml.criterion.EntityRoleCriterion;
+import org.opensaml.saml.metadata.resolver.filter.MetadataFilter;
+import org.opensaml.saml.metadata.resolver.filter.MetadataFilterChain;
+import org.opensaml.saml.metadata.resolver.filter.impl.RequiredValidUntilFilter;
+import org.opensaml.saml.metadata.resolver.impl.PredicateRoleDescriptorResolver;
+import org.opensaml.saml.saml2.metadata.EntityDescriptor;
+import org.opensaml.saml.saml2.metadata.RequestedAttribute;
+import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
+import org.opensaml.saml.security.impl.MetadataCredentialResolver;
+import org.opensaml.security.credential.Credential;
+import org.opensaml.security.credential.UsageType;
+import org.opensaml.security.criteria.UsageCriterion;
+import org.opensaml.security.x509.BasicX509Credential;
+import org.opensaml.xmlsec.SignatureValidationConfiguration;
+import org.opensaml.xmlsec.SignatureValidationParameters;
+import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver;
+import org.opensaml.xmlsec.keyinfo.impl.BasicProviderKeyInfoCredentialResolver;
+import org.opensaml.xmlsec.keyinfo.impl.KeyInfoProvider;
+import org.opensaml.xmlsec.keyinfo.impl.provider.DSAKeyValueProvider;
+import org.opensaml.xmlsec.keyinfo.impl.provider.InlineX509DataProvider;
+import org.opensaml.xmlsec.keyinfo.impl.provider.RSAKeyValueProvider;
+import org.opensaml.xmlsec.signature.support.SignatureValidationParametersCriterion;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.w3c.dom.Element;
+
+import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
+import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
+import net.shibboleth.utilities.java.support.resolver.ResolverException;
+import net.shibboleth.utilities.java.support.xml.SerializeSupport;
+import net.shibboleth.utilities.java.support.xml.XMLParserException;
+import okhttp3.HttpUrl;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({ "/spring/test_eaaf_pvp.beans.xml",
+ "/spring/test_eaaf_core_spring_config.beans.xml",
+ "/spring/eaaf_utils.beans.xml" })
+@TestPropertySource(locations = { "/config/config_1.props" })
+public class MetadataResolverTest {
+
+ private static MockWebServer mockWebServer;
+ private static HttpUrl mockServerUrl;
+
+ @Autowired
+ private PvpMetadataResolverFactory metadataResolverFactory;
+ @Autowired
+ private IHttpClientFactory httpClientFactory;
+ @Autowired private DummyCredentialProvider credentialProvider;
+
+ /**
+ * JUnit class initializer.
+ *
+ * @throws Exception In case of an OpenSAML3 initialization error
+ */
+ @BeforeClass
+ public static void classInitializer() throws Exception {
+ EaafOpenSaml3xInitializer.eaafInitialize();
+ mockWebServer = new MockWebServer();
+ mockServerUrl = mockWebServer.url("/sp/metadata");
+
+ }
+
+ /**
+ * Single test initializer.
+ *
+ */
+ @Before
+ public void testInitializer() {
+
+ }
+
+ @Test
+ public void wrongSchema() {
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ try {
+ metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_schema.xml",
+ filterChain, "jUnit test", null);
+ Assert.fail("Wrong XML Schema not detected");
+
+ } catch (final Pvp2MetadataException e) {
+ Assert.assertEquals("Wrong ErrorCode", "internal.pvp.08", e.getErrorId());
+ Assert.assertNotNull("params null", e.getParams());
+ Assert.assertEquals("Params size", 2, e.getParams().length);
+ Assert.assertEquals("Param[0] wrong",
+ "classpath:/data/pvp_metadata_wrong_schema.xml", e.getParams()[0]);
+
+ }
+
+ }
+
+ @Test
+ public void simpleClasspathMetadataWithoutSigValidation()
+ throws Pvp2MetadataException, ComponentInitializationException, ResolverException,
+ Pvp2InternalErrorException {
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_wrong_sig.xml",
+ filterChain, "jUnit test", null);
+
+ final EntityDescriptor entityIdNotExists = mdResolver.getEntityDescriptor(
+ "https://demo.egiz.gv.at/notExtist/");
+ Assert.assertNull("No EntityDescripter", entityIdNotExists);
+
+ final EntityDescriptor entityId = mdResolver.getEntityDescriptor(
+ "https://demo.egiz.gv.at/demoportal_demologin/");
+ Assert.assertNotNull("No EntityDescripter", entityId);
+
+ Assert.assertNotNull("Metadata provider is null", mdResolver);
+ final MetadataCredentialResolver resolver = createKeyInfoResolver(mdResolver);
+
+ final CriteriaSet criteriaSet = new CriteriaSet();
+ criteriaSet.add(new EntityIdCriterion("https://demo.egiz.gv.at/demoportal_demologin/"));
+ criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
+ criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
+ final SignatureValidationParameters sigValCrit = new SignatureValidationParameters();
+ sigValCrit.setBlacklistedAlgorithms(
+ ConfigurationService.get(SignatureValidationConfiguration.class)
+ .getBlacklistedAlgorithms());
+ sigValCrit.setSignatureTrustEngine(
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(mdResolver));
+ criteriaSet.add(new SignatureValidationParametersCriterion(sigValCrit));
+
+ final Iterable<Credential> keyInfos = resolver.resolve(criteriaSet);
+ Assert.assertNotNull("KeyInfos null", keyInfos);
+
+ }
+
+ @Test
+ public void noCredentials() {
+ final String metadataUrl = "classpath:/data/pvp_metadata_moaid_test.xml";
+
+ final List<BasicX509Credential> credentials = new ArrayList<>();
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ filterList.add(new SimpleMetadataSignatureVerificationFilter(
+ credentials,
+ metadataUrl));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ try {
+ metadataResolverFactory.createMetadataProvider(
+ metadataUrl,
+ filterChain, "jUnit test", null);
+ Assert.fail("Untrusted signature not detected");
+
+ } catch (final Pvp2MetadataException e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.07", e.getErrorId());
+
+ }
+
+ }
+
+ @Test
+ public void wrongCredentials() throws CertificateException {
+ final String metadataUrl = "classpath:/data/pvp_metadata_moaid_test.xml";
+
+ final List<BasicX509Credential> credentials = new ArrayList<>();
+ final CertificateFactory fact = CertificateFactory.getInstance("X.509");
+ final BasicX509Credential credential = new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/assertion_sig_cert.crt")));
+ credentials.add(credential);
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ filterList.add(new SimpleMetadataSignatureVerificationFilter(
+ credentials,
+ metadataUrl));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ try {
+ metadataResolverFactory.createMetadataProvider(
+ metadataUrl,
+ filterChain, "jUnit test", null);
+ Assert.fail("Untrusted signature not detected");
+
+ } catch (final Pvp2MetadataException e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.07", e.getErrorId());
+
+ }
+
+ }
+
+ @Test
+ public void validCredentialsInvalidSig() throws CertificateException, Pvp2MetadataException,
+ ResolverException {
+ final String metadataUrl = "classpath:/data/pvp_metadata_moaid_test.xml";
+
+ final List<BasicX509Credential> credentials = new ArrayList<>();
+ final CertificateFactory fact = CertificateFactory.getInstance("X.509");
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/assertion_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/metadata_sig_cert.crt"))));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ filterList.add(new SimpleMetadataSignatureVerificationFilter(
+ credentials,
+ metadataUrl));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+ try {
+ metadataResolverFactory.createMetadataProvider(
+ metadataUrl,
+ filterChain, "jUnit test", null);
+ Assert.fail("Untrusted signature not detected");
+
+ } catch (final Pvp2MetadataException e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.07", e.getErrorId());
+
+ }
+
+ }
+
+ @Test
+ public void metadataSignatureValidCredentials() throws CertificateException, Pvp2MetadataException,
+ ResolverException, XMLParserException, UnmarshallingException, SamlSigningException,
+ CredentialsNotAvailableException, MarshallingException, TransformerException, IOException {
+
+ mockWebServer.shutdown();
+ mockWebServer = new MockWebServer();
+ mockServerUrl = mockWebServer.url("/sp/metadata");
+
+ final EntityDescriptor metadata = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ MetadataResolverTest.class.getResourceAsStream("/data/pvp_metadata_moaid_test.xml"));
+ metadata.setValidUntil(DateTime.now().plusDays(1));
+ metadata.setSignature(null);
+ metadata.setEntityID(RandomStringUtils.randomAlphabetic(10));
+ final EntityDescriptor signedMatadata =
+ Saml2Utils.signSamlObject(metadata, credentialProvider.getMetaDataSigningCredential(), true);
+ final Element metadataElement = XMLObjectSupport.marshall(signedMatadata);
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(SerializeSupport.nodeToString(metadataElement))
+ .setHeader("Content-Type", "text/html;charset=utf-8"));
+
+ final List<BasicX509Credential> credentials = new ArrayList<>();
+ final CertificateFactory fact = CertificateFactory.getInstance("X.509");
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/metadata_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/assertion_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/junit_metadata_sig_cert.crt"))));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+ filterList.add(new SimpleMetadataSignatureVerificationFilter(
+ credentials,
+ mockServerUrl.url().toString()));
+ filterList.add(new PvpEntityCategoryFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+
+ final EntityDescriptor entityIdNotExists = mdResolver.getEntityDescriptor(
+ metadata.getEntityID());
+ Assert.assertNotNull("No EntityDescripter", entityIdNotExists);
+
+ }
+
+ @Test
+ public void metadataSignatureValidCredentialsSecond() throws CertificateException, Pvp2MetadataException,
+ ResolverException, XMLParserException, UnmarshallingException, SamlSigningException,
+ CredentialsNotAvailableException, MarshallingException, TransformerException, IOException {
+
+ final EntityDescriptor metadata = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ MetadataResolverTest.class.getResourceAsStream("/data/pvp_metadata_valid_with_entityCategory.xml"));
+ metadata.setValidUntil(DateTime.now().plusDays(1));
+ metadata.setSignature(null);
+ metadata.setEntityID(RandomStringUtils.randomAlphabetic(10));
+ final EntityDescriptor signedMatadata =
+ Saml2Utils.signSamlObject(metadata, credentialProvider.getMetaDataSigningCredential(), true);
+ final Element metadataElement = XMLObjectSupport.marshall(signedMatadata);
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(SerializeSupport.nodeToString(metadataElement))
+ .setHeader("Content-Type", "text/html;charset=utf-8"));
+
+ final List<BasicX509Credential> credentials = new ArrayList<>();
+ final CertificateFactory fact = CertificateFactory.getInstance("X.509");
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/metadata_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/assertion_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/junit_metadata_sig_cert.crt"))));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+ filterList.add(new SimpleMetadataSignatureVerificationFilter(
+ credentials,
+ mockServerUrl.url().toString()));
+ filterList.add(new PvpEntityCategoryFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+
+
+
+ final EntityDescriptor descr = mdResolver.getEntityDescriptor(metadata.getEntityID());
+ Assert.assertNotNull("No EntityDescripter", descr);
+
+ final List<RequestedAttribute> reqAttr = descr.getSPSSODescriptor(SAMLConstants.SAML20P_NS)
+ .getAttributeConsumingServices().get(0).getRequestAttributes();
+ Assert.assertNotNull("Req. attributes are null", reqAttr);
+ Assert.assertEquals("# of req. attributes", 20, reqAttr.size());
+
+ }
+
+ @Test
+ public void metadataSignatureValidCredentialsThird() throws CertificateException, Pvp2MetadataException,
+ ResolverException, XMLParserException, UnmarshallingException, SamlSigningException,
+ CredentialsNotAvailableException, MarshallingException, TransformerException, IOException {
+
+ final EntityDescriptor metadata = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ MetadataResolverTest.class.getResourceAsStream("/data/pvp_metadata_valid_with_entityCategory_egov.xml"));
+ metadata.setValidUntil(DateTime.now().plusDays(1));
+ metadata.setSignature(null);
+ metadata.setEntityID(RandomStringUtils.randomAlphabetic(10));
+ final EntityDescriptor signedMatadata =
+ Saml2Utils.signSamlObject(metadata, credentialProvider.getMetaDataSigningCredential(), true);
+ final Element metadataElement = XMLObjectSupport.marshall(signedMatadata);
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(SerializeSupport.nodeToString(metadataElement))
+ .setHeader("Content-Type", "text/html;charset=utf-8"));
+
+ final List<BasicX509Credential> credentials = new ArrayList<>();
+ final CertificateFactory fact = CertificateFactory.getInstance("X.509");
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/metadata_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/assertion_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/junit_metadata_sig_cert.crt"))));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+ filterList.add(new SimpleMetadataSignatureVerificationFilter(
+ credentials,
+ mockServerUrl.url().toString()));
+ filterList.add(new PvpEntityCategoryFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+
+
+
+ final EntityDescriptor descr = mdResolver.getEntityDescriptor(metadata.getEntityID());
+ Assert.assertNotNull("No EntityDescripter", descr);
+
+ final List<RequestedAttribute> reqAttr = descr.getSPSSODescriptor(SAMLConstants.SAML20P_NS)
+ .getAttributeConsumingServices().get(0).getRequestAttributes();
+ Assert.assertNotNull("Req. attributes are null", reqAttr);
+ Assert.assertEquals("# of req. attributes", 9, reqAttr.size());
+
+ }
+
+ @Test
+ public void metadataExpired() throws CertificateException, Pvp2MetadataException,
+ ResolverException, XMLParserException, UnmarshallingException, SamlSigningException,
+ CredentialsNotAvailableException, MarshallingException, TransformerException, IOException {
+
+ final EntityDescriptor metadata = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream(
+ XMLObjectProviderRegistrySupport.getParserPool(),
+ MetadataResolverTest.class.getResourceAsStream("/data/pvp_metadata_valid.xml"));
+ metadata.setValidUntil(DateTime.now().minusDays(2));
+ metadata.setSignature(null);
+ Saml2Utils.signSamlObject(metadata, credentialProvider.getMetaDataSigningCredential(), true);
+ final Element metadataElement = XMLObjectSupport.marshall(metadata);
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(SerializeSupport.nodeToString(metadataElement))
+ .setHeader("Content-Type", "text/html;charset=utf-8"));
+
+ final List<BasicX509Credential> credentials = new ArrayList<>();
+ final CertificateFactory fact = CertificateFactory.getInstance("X.509");
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/metadata_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/assertion_sig_cert.crt"))));
+ credentials.add(new BasicX509Credential((X509Certificate) fact.generateCertificate(
+ MetadataResolverTest.class.getResourceAsStream("/data/junit_metadata_sig_cert.crt"))));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+ filterList.add(new SimpleMetadataSignatureVerificationFilter(
+ credentials,
+ mockServerUrl.url().toString()));
+ filterList.add(new RequiredValidUntilFilter());
+ filterList.add(new PvpEntityCategoryFilter(false));
+
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ try {
+ metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+ Assert.fail("Expired metadata not detected");
+
+ } catch (final Pvp2MetadataException e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.09", e.getErrorId());
+
+ }
+
+
+ }
+
+ @Test
+ public void simpleClasspathMetadataWithoutSigValidationMoaidTwoSigKeys()
+ throws Pvp2MetadataException, ComponentInitializationException, ResolverException,
+ Pvp2InternalErrorException {
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final String entityIdToResolve = "https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/metadata";
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ "classpath:/data/pvp_metadata_moaid_test.xml",
+ filterChain, "jUnit test", null);
+
+ final EntityDescriptor entityIdNotExists = mdResolver.getEntityDescriptor(
+ "https://demo.egiz.gv.at/notExtist/");
+ Assert.assertNull("No EntityDescripter", entityIdNotExists);
+
+ final EntityDescriptor entityId = mdResolver.getEntityDescriptor(entityIdToResolve);
+ Assert.assertNotNull("No EntityDescripter", entityId);
+
+ Assert.assertNotNull("Metadata provider is null", mdResolver);
+ final MetadataCredentialResolver resolver = createKeyInfoResolver(mdResolver);
+
+ final CriteriaSet sigCriteriaSet = new CriteriaSet();
+ sigCriteriaSet.add(new EntityIdCriterion(entityIdToResolve));
+ sigCriteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
+ sigCriteriaSet.add(new UsageCriterion(UsageType.SIGNING));
+ final SignatureValidationParameters sigValCrit = new SignatureValidationParameters();
+ sigValCrit.setBlacklistedAlgorithms(
+ ConfigurationService.get(SignatureValidationConfiguration.class)
+ .getBlacklistedAlgorithms());
+ sigValCrit.setSignatureTrustEngine(
+ TrustEngineFactory.getSignatureKnownKeysTrustEngine(mdResolver));
+ sigCriteriaSet.add(new SignatureValidationParametersCriterion(sigValCrit));
+
+ final Iterable<Credential> singingKeyInfos = resolver.resolve(sigCriteriaSet);
+ Assert.assertNotNull("Signing KeyInfos null", singingKeyInfos);
+ Assert.assertTrue("First Credential resolved", singingKeyInfos.iterator().hasNext());
+ Assert.assertTrue("Second Credential resolved", singingKeyInfos.iterator().hasNext());
+
+ final CriteriaSet encCriteriaSet = new CriteriaSet();
+ encCriteriaSet.add(new EntityIdCriterion(entityIdToResolve));
+ encCriteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
+ encCriteriaSet.add(new UsageCriterion(UsageType.ENCRYPTION));
+ final Iterable<Credential> encKeyInfos = resolver.resolve(encCriteriaSet);
+ Assert.assertNotNull("Encryption KeyInfos null", encKeyInfos);
+ Assert.assertTrue("No Credential resolved", encKeyInfos.iterator().hasNext());
+
+ }
+
+ @Test
+ public void httpMetadataLoading() throws UnsupportedEncodingException,
+ IOException, ResolverException, Pvp2MetadataException {
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_moaid_test.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final String entityIdToResolve = "https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/metadata";
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+
+ final EntityDescriptor entityIdNotExists = mdResolver.getEntityDescriptor(
+ "https://demo.egiz.gv.at/notExtist/");
+ Assert.assertNull("No EntityDescripter", entityIdNotExists);
+
+ final EntityDescriptor entityId = mdResolver.getEntityDescriptor(entityIdToResolve);
+ Assert.assertNotNull("No EntityDescripter", entityId);
+
+ }
+
+ @Test
+ public void httpMetadataLoadingRefeshFailed() throws UnsupportedEncodingException,
+ IOException, ResolverException, Pvp2MetadataException {
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_moaid_test.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final String entityIdToResolve = "https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/metadata";
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+
+ final EntityDescriptor entityIdNotExists = mdResolver.getEntityDescriptor(
+ "https://demo.egiz.gv.at/notExtist/");
+ Assert.assertNull("No EntityDescripter", entityIdNotExists);
+
+ final EntityDescriptor entityId = mdResolver.getEntityDescriptor(entityIdToResolve);
+ Assert.assertNotNull("No EntityDescripter", entityId);
+
+ final DateTime lastRefreshSucess = mdResolver.getLastSuccessfulRefresh();
+
+ try {
+ mdResolver.refresh();
+ Assert.fail("Refesh possible without available metadata");
+
+ } catch (final ResolverException e) {
+ Assert.assertFalse("Wrong Refesh success flag", mdResolver.wasLastRefreshSuccess());
+ Assert.assertEquals("Wrong refresh success date", lastRefreshSucess, mdResolver
+ .getLastSuccessfulRefresh());
+
+ }
+
+ }
+
+ @Test
+ public void httpMetadataLoadingWithRefeshSuccess() throws UnsupportedEncodingException,
+ IOException, ResolverException, Pvp2MetadataException {
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_moaid_test.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_moaid_test.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ final String entityIdToResolve = "https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/metadata";
+
+ final IPvp2MetadataProvider mdResolver = metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+
+ final EntityDescriptor entityIdNotExists = mdResolver.getEntityDescriptor(
+ "https://demo.egiz.gv.at/notExtist/");
+ Assert.assertNull("No EntityDescripter", entityIdNotExists);
+
+ final EntityDescriptor entityId = mdResolver.getEntityDescriptor(entityIdToResolve);
+ Assert.assertNotNull("No EntityDescripter", entityId);
+
+ // refresh metadata
+ mdResolver.refresh();
+
+ Assert.assertTrue("Refresh not sucessful", mdResolver.wasLastRefreshSuccess());
+
+ }
+
+ @Test
+ public void httpMetadataLoadingWithoutHttpClient() throws UnsupportedEncodingException,
+ IOException, ResolverException, Pvp2MetadataException {
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_moaid_test.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ try {
+ metadataResolverFactory.createMetadataProvider(
+ mockServerUrl.url().toString(),
+ filterChain, "jUnit test", null);
+ Assert.fail("No httpclient not detected");
+
+ } catch (final Pvp2MetadataException e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.09", e.getErrorId());
+ Assert.assertNotNull("No error params", e.getParams());
+ Assert.assertEquals("Wrong params size", 2, e.getParams().length);
+
+ }
+ }
+
+ @Test
+ public void httpMetadataLoadingWrongUrl() throws UnsupportedEncodingException,
+ IOException, ResolverException, Pvp2MetadataException {
+
+ mockWebServer.enqueue(new MockResponse().setResponseCode(200)
+ .setBody(new String(IOUtils.toByteArray(
+ MetadataResolverTest.class.getResourceAsStream(
+ "/data/pvp_metadata_moaid_test.xml")), "UTF-8"))
+ .setHeader("Content-Type", "text/xml"));
+
+ final List<MetadataFilter> filterList = new ArrayList<>();
+ filterList.add(new SchemaValidationFilter(true));
+
+ final MetadataFilterChain filterChain = new MetadataFilterChain();
+ filterChain.setFilters(filterList);
+
+ try {
+ metadataResolverFactory.createMetadataProvider(
+ "http://127.0.0.1/notexist",
+ filterChain, "jUnit test", httpClientFactory.getHttpClient());
+ Assert.fail("No httpclient not detected");
+
+ } catch (final Pvp2MetadataException e) {
+ Assert.assertEquals("Wrong errorCode", "internal.pvp.09", e.getErrorId());
+ Assert.assertNotNull("No error params", e.getParams());
+ Assert.assertEquals("Wrong params size", 2, e.getParams().length);
+
+ }
+
+ }
+
+ private MetadataCredentialResolver createKeyInfoResolver(IPvp2MetadataProvider mdResolver)
+ throws ComponentInitializationException {
+ final List<KeyInfoProvider> keyInfoProvider = new ArrayList<>();
+ keyInfoProvider.add(new DSAKeyValueProvider());
+ keyInfoProvider.add(new RSAKeyValueProvider());
+ keyInfoProvider.add(new InlineX509DataProvider());
+ final KeyInfoCredentialResolver keyInfoCredentialResolver = new BasicProviderKeyInfoCredentialResolver(
+ keyInfoProvider);
+
+ final PredicateRoleDescriptorResolver roleDescriptorResolver = new PredicateRoleDescriptorResolver(
+ mdResolver);
+ roleDescriptorResolver.setRequireValidMetadata(true);
+ roleDescriptorResolver.initialize();
+
+ final MetadataCredentialResolver resolver = new MetadataCredentialResolver();
+ resolver.setRoleDescriptorResolver(roleDescriptorResolver);
+ resolver.setKeyInfoCredentialResolver(keyInfoCredentialResolver);
+ resolver.initialize();
+
+ return resolver;
+ }
+}