From f696b4085fd10b3b9d627437f439b222903e13e1 Mon Sep 17 00:00:00 2001 From: lalber Date: Tue, 20 Oct 2020 07:47:44 +0200 Subject: stuck on how to test --- .gitignore | 1 + .../specific/connector/MsEidasNodeConstants.java | 2 + eidas_modules/authmodule-eIDAS-v2/pom.xml | 33 +- .../modules/auth/eidas/v2/szr/SzrClient.java | 119 +++++- .../eidas/v2/tasks/CreateIdentityLinkTask.java | 141 ++++--- .../modules/auth/eidas/v2/utils/JoseUtils.java | 305 ++++++++++++++ .../src/main/resources/szr_client/SZR_v4.0.wsdl | 441 ++++++++++++++++++++ .../src/main/resources/szr_client/pvp19.xsd | 133 +++++++ .../src/main/resources/szr_client/szr_ecdsa.xsd | 30 ++ .../main/resources/szr_client/szr_persondata.xsd | 54 +++ .../src/main/resources/szr_client/szr_pvp_sec.xsd | 10 + .../main/resources/szr_client/szr_v4.0-schemas.xml | 54 +++ .../main/resources/szr_client/szr_v4.0-wsdl.xml | 10 + .../src/main/resources/szr_client/szr_v4.0.xsd | 443 +++++++++++++++++++++ .../src/main/resources/szr_client/szr_xmldsig.xsd | 31 ++ .../modules/auth/eidas/v2/test/SzrClientTest.java | 76 +++- .../eidas/v2/test/SzrClientTestProduction.java | 12 +- .../CreateIdentityLinkTaskEidNewSimpleTest.java | 119 ++++++ .../tasks/CreateIdentityLinkTaskEidNewTest.java | 217 ++++++++++ .../resources/config/junit_config_3.properties | 109 +++++ .../src/test/resources/keystore/teststore.jks | Bin 0 -> 2028 bytes 21 files changed, 2247 insertions(+), 93 deletions(-) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/utils/JoseUtils.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/SZR_v4.0.wsdl create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/pvp19.xsd create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_ecdsa.xsd create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_persondata.xsd create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_pvp_sec.xsd create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-schemas.xml create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-wsdl.xml create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0.xsd create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_xmldsig.xsd create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/teststore.jks diff --git a/.gitignore b/.gitignore index d70ac7c0..9be35422 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ target .directory .checkstyle .metadata +*.iml notCommit diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java index c28e753a..f33ccf44 100644 --- a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java @@ -94,6 +94,8 @@ public class MsEidasNodeConstants { public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE = "pvp2.metadata.truststore"; public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE_PASSWORD = "pvp2.metadata.truststore.password"; + public static final String PROP_CONFIG_SP_EID_MODE = + "eidMode"; public static final String PROP_CONFIG_SP_POLICY_ALLOWED_TARGETS = "policy.allowed.requested.targets"; public static final String PROP_CONFIG_SP_POLICY_BASEIDTRANSFER_RESTRICTION = "policy.hasBaseIdTransferRestriction"; diff --git a/eidas_modules/authmodule-eIDAS-v2/pom.xml b/eidas_modules/authmodule-eIDAS-v2/pom.xml index e64aefc7..7bbdaf78 100644 --- a/eidas_modules/authmodule-eIDAS-v2/pom.xml +++ b/eidas_modules/authmodule-eIDAS-v2/pom.xml @@ -148,6 +148,24 @@ mockito-soap-cxf test + + org.powermock + powermock-module-junit4 + 2.0.7 + test + + + org.powermock + powermock-api-mockito2 + 2.0.7 + test + + + eu.eidas + eidas-light-commons + 2.4.0 + test + at.gv.egiz.eaaf eaaf_core_utils @@ -160,6 +178,17 @@ test test-jar + + com.fasterxml.jackson.core + jackson-databind + 2.11.2 + compile + + + org.bitbucket.b_c + jose4j + 0.7.2 + @@ -168,7 +197,7 @@ src/main/resources - target/generated/cxf + target/generated-sources/cxf @@ -209,7 +238,7 @@ ${project.build.directory}/generated/cxf - ${basedir}/src/main/resources/szr_client/SZR-1.1.WSDL + ${basedir}/src/main/resources/szr_client/SZR_v4.0.wsdl -verbose diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java index 763d8dab..5a551649 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java @@ -33,9 +33,7 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import javax.annotation.PostConstruct; import javax.net.ssl.KeyManager; @@ -56,7 +54,10 @@ import javax.xml.ws.BindingProvider; import javax.xml.ws.Dispatch; import javax.xml.ws.handler.Handler; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.StopWatch; import org.apache.cxf.configuration.jsse.TLSClientParameters; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; @@ -79,15 +80,7 @@ import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.impl.utils.DomUtils; import at.gv.egiz.eaaf.core.impl.utils.FileUtils; import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; -import szrservices.GetBPK; -import szrservices.GetBPKResponse; -import szrservices.GetIdentityLinkEidas; -import szrservices.GetIdentityLinkEidasResponse; -import szrservices.IdentityLinkType; -import szrservices.ObjectFactory; -import szrservices.PersonInfoType; -import szrservices.SZR; -import szrservices.SZRException_Exception; +import szrservices.*; @Service("SZRClientForeIDAS") public class SzrClient { @@ -109,9 +102,11 @@ public class SzrClient { private String szrUrl = null; private QName qname = null; + final ObjectMapper mapper = new ObjectMapper(); + /** * Get IdentityLink of a person. - * + * * @param personInfo Person identification information * @return IdentityLink * @throws SzrCommunicationException In case of a SZR error @@ -165,7 +160,7 @@ public class SzrClient { } catch (final Exception e) { log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); - throw new SzrCommunicationException("ernb.02", new Object[] { e.getMessage() }, e); + throw new SzrCommunicationException("ernb.02", new Object[]{e.getMessage()}, e); } @@ -173,19 +168,19 @@ public class SzrClient { /** * Get bPK of person. - * + * * @param personInfo Person identification information - * @param target requested bPK target - * @param vkz Verfahrenskennzeichen + * @param target requested bPK target + * @param vkz Verfahrenskennzeichen * @return bPK for this person * @throws SzrCommunicationException In case of a SZR error */ - public String getBpk(PersonInfoType personInfo, String target, String vkz) + public List getBpk(PersonInfoType personInfo, String target, String vkz) throws SzrCommunicationException { try { final GetBPK parameters = new GetBPK(); parameters.setPersonInfo(personInfo); - parameters.setBereichsKennung(target); + parameters.getBereichsKennung().add(target); parameters.setVKZ(vkz); final GetBPKResponse result = this.szr.getBPK(parameters); @@ -193,16 +188,98 @@ public class SzrClient { } catch (final SZRException_Exception e) { log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); - throw new SzrCommunicationException("ernb.02", new Object[] { e.getMessage() }, e); + throw new SzrCommunicationException("ernb.02", new Object[]{e.getMessage()}, e); } } + /** + * Request a encryped baseId from SRZ. + * + * @param personInfo Minimum dataset of person + * @return encrypted baseId + * @throws SzrCommunicationException In case of a SZR error + */ + public String getEncryptedStammzahl(final PersonInfoType personInfo) + throws SzrCommunicationException { + + final String resp; + try { + resp = this.szr.getStammzahlEncrypted(personInfo, false); + } catch (SZRException_Exception e) { + throw new SzrCommunicationException("ernb.02", new Object[]{e.getMessage()}, e); + } + + if (resp == null || StringUtils.isEmpty(resp)) { + throw new SzrCommunicationException("ernb.01", new Object[]{"Stammzahl response empty"}); // TODO error handling + } + + return resp; + + } + + + /** + * Signs content. + * + * @param vsz ? TODO + * @param bindingPubKey binding PublikKey as PKCS1# (ASN.1) container + * @param eidStatus Status of the E-ID + * @return bPK for this person + * @throws SzrCommunicationException In case of a SZR error + */ + public String getBcBind(final String vsz, final String bindingPubKey, final String eidStatus) + throws SzrCommunicationException { + + final String ATTR_NAME_VSZ = "urn:eidgvat:attributes.vsz.value"; + final String ATTR_NAME_PUBKEYS = "urn:eidgvat:attributes.user.pubkeys"; + final String ATTR_NAME_STATUS = "urn:eidgvat:attributes.eid.status"; + final String KEY_BC_BIND = "bcBindReq"; + final String JOSE_HEADER_USERCERTPINNING_TYPE = "urn:at.gv.eid:bindtype"; + final String JOSE_HEADER_USERCERTPINNING_EIDASBIND = "urn:at.gv.eid:eidasBind"; + + final Map bcBindMap = new HashMap<>(); + bcBindMap.put(ATTR_NAME_VSZ, vsz); + bcBindMap.put(ATTR_NAME_STATUS, eidStatus); + bcBindMap.put(ATTR_NAME_PUBKEYS, Arrays.asList(bindingPubKey)); + + try { + final String serializedBcBind = mapper.writeValueAsString(bcBindMap); + final SignContent req = new SignContent(); + final SignContentEntry bcBindInfo = new SignContentEntry(); + bcBindInfo.setKey(KEY_BC_BIND); + bcBindInfo.setValue(serializedBcBind); + req.getIn().add(bcBindInfo); + req.setAppendCert(false); + final JwsHeaderParam bcBindJoseHeader = new JwsHeaderParam(); + bcBindJoseHeader.setKey(JOSE_HEADER_USERCERTPINNING_TYPE); + bcBindJoseHeader.setValue(JOSE_HEADER_USERCERTPINNING_EIDASBIND); + req.getJWSHeaderParam().add(bcBindJoseHeader); + + log.trace("Requesting SZR to sign bcBind datastructure ... "); + final SignContentResponseType resp = szr.signContent(req.isAppendCert(), req.getJWSHeaderParam(), req.getIn()); + log.trace("Receive SZR response on bcBind siging operation "); + + if (resp == null + || resp.getOut().isEmpty() + || resp.getOut().get(0).getValue() == null) { + throw new SzrCommunicationException("ernb.01", new Object[]{"BcBind response empty"}); //TODO check error handling + } + + return resp.getOut().get(0).getValue(); + + } catch (final JsonProcessingException | SZRException_Exception e) { + log.warn("Requesting bcBind by using SZR FAILED. Reason: {}", e.getMessage(), null, e); + throw new SzrCommunicationException("ernb.02", + new Object[]{e.getMessage()}, e); + } + } + @PostConstruct private void initialize() { log.info("Starting SZR-Client initialization .... "); - final URL url = SzrClient.class.getResource("/szr_client/SZR-1.1.WSDL"); + final URL url = SzrClient.class.getResource("/szr_client/SZR_v4.0.wsdl"); final boolean useTestSzr = basicConfig.getBasicConfigurationBoolean( Constants.CONIG_PROPS_EIDAS_SZRCLIENT_USETESTSERVICE, diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index 88c3515b..e4a22cbc 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -19,28 +19,10 @@ * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - import at.asitplus.eidas.specific.connector.MsConnectorEventCodes; import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; @@ -60,6 +42,8 @@ import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +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.data.Pair; import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; @@ -67,20 +51,38 @@ import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egiz.eaaf.core.impl.utils.DomUtils; import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import eu.eidas.auth.commons.attribute.AttributeDefinition; import eu.eidas.auth.commons.attribute.AttributeValue; import eu.eidas.auth.commons.light.ILightResponse; import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; import lombok.extern.slf4j.Slf4j; +import lombok.val; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.w3c.dom.Element; +import org.w3c.dom.Node; import szrservices.IdentityLinkType; import szrservices.PersonInfoType; import szrservices.TravelDocumentType; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.InputStream; +import java.security.KeyStoreException; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * Task that creates the IdentityLink for an eIDAS authenticated person. - * - * @author tlenz * + * @author tlenz */ @Slf4j @Component("CreateIdentityLinkTask") @@ -95,7 +97,7 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { /* * (non-Javadoc) - * + * * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv. * egovernment.moa.id.process.api.ExecutionContext, * javax.servlet.http.HttpServletRequest, @@ -103,7 +105,7 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { */ @Override public void execute(ExecutionContext executionContext, - HttpServletRequest request, HttpServletResponse response) + HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { try { final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); @@ -217,43 +219,64 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(personInfo); + String eidMode = pendingReq.getServiceProviderConfiguration().getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); + if (eidMode.equals("new")) { - final Element idlFromSzr = (Element) result.getAssertion(); - identityLink = new SimpleIdentityLinkAssertionParser(idlFromSzr).parseIdentityLink(); + String vsz = szrClient.getEncryptedStammzahl(personInfo); - // write ERnB inputdata into revisionlog - if (basicConfig.getBasicConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_WORKAROUND_REVISIONLOGDATASTORE_ACTIVE, false)) { - revisionsLogger.logEvent(pendingReq, - MsConnectorEventCodes.SZR_ERNB_EIDAS_RAW_ID, - (String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)); - revisionsLogger.logEvent(pendingReq, - MsConnectorEventCodes.SZR_ERNB_EIDAS_ERNB_ID, eidData.getPseudonym()); + // build Keystore + String pK64 = getPkFromKeystore(); + // setzte Keystore in config ?path? lade rein + // key pair art siehe jose utils - } - // get bPK from SZR - if (basicConfig.getBasicConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { - bpk = szrClient.getBpk( - personInfo, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, - "no VKZ defined")); + String signedEidasBind = szrClient.getBcBind(vsz, pK64, "urn:eidgvat:eid.status.eidas"); //eidstatus TODO as config? + + //build AuthBlock JWS + ObjectMapper mapper = new ObjectMapper(); + String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); + +// JoseUtils.createSignature(new Pair<>(ks, ks.getProvider()), "connectorkeypair", passord.chararray(), jwsPayload, false, ); //TODO joseutils kopiern } else { - log.debug("Calculating bPK from baseId ... "); - new BpkBuilder(); - final Pair bpkCalc = BpkBuilder.generateAreaSpecificPersonIdentifier( - identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); - bpk = bpkCalc.getFirst(); - } + final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(personInfo); + final Element idlFromSzr = (Element) result.getAssertion(); + identityLink = new SimpleIdentityLinkAssertionParser(idlFromSzr).parseIdentityLink(); + + // write ERnB inputdata into revisionlog + if (basicConfig.getBasicConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_WORKAROUND_REVISIONLOGDATASTORE_ACTIVE, false)) { + revisionsLogger.logEvent(pendingReq, + MsConnectorEventCodes.SZR_ERNB_EIDAS_RAW_ID, + (String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)); + revisionsLogger.logEvent(pendingReq, + MsConnectorEventCodes.SZR_ERNB_EIDAS_ERNB_ID, eidData.getPseudonym()); + + } + + // get bPK from SZR + if (basicConfig.getBasicConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { + bpk = szrClient.getBpk( + personInfo, + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), + basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, + "no VKZ defined")).get(0); + + } else { + log.debug("Calculating bPK from baseId ... "); + new BpkBuilder(); + final Pair bpkCalc = BpkBuilder.generateAreaSpecificPersonIdentifier( + identityLink.getIdentificationValue(), + identityLink.getIdentificationType(), + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + bpk = bpkCalc.getFirst(); + + } + } } if (identityLink == null) { @@ -307,6 +330,20 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } + private String getPkFromKeystore() throws EaafException, KeyStoreException { + EaafKeyStoreFactory keyStoreFactory = new EaafKeyStoreFactory(); + KeyStoreConfiguration configuration = new KeyStoreConfiguration(); + + final String current = new java.io.File(".").toURI().toString(); + configuration.setSoftKeyStoreFilePath(current + "src/test/resources/keystore/teststore.jks"); + + configuration.setSoftKeyStorePassword("f/+saJBc3a}*/T^s"); + configuration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.JKS); + val ks = keyStoreFactory.buildNewKeyStore(configuration); + val publicKey = ks.getFirst().getCertificate("connectorkeypair").getPublicKey(); + return Base64.getEncoder().encodeToString(publicKey.getEncoded()); + } + private String extendBpkByPrefix(String bpk, String type) { String bpkType = null; diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/utils/JoseUtils.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/utils/JoseUtils.java new file mode 100644 index 00000000..e81c4c92 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/utils/JoseUtils.java @@ -0,0 +1,305 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.utils; + +import at.gv.egiz.eaaf.core.exception.EaafKeyUsageException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreUtils; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.utils.X509Utils; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.jose4j.jca.ProviderContext; +import org.jose4j.jwa.AlgorithmConstraints; +import org.jose4j.jws.AlgorithmIdentifiers; +import org.jose4j.jws.JsonWebSignature; +import org.jose4j.jwx.Headers; +import org.jose4j.jwx.JsonWebStructure; +import org.jose4j.keys.resolvers.X509VerificationKeyResolver; +import org.jose4j.lang.JoseException; +import org.springframework.util.Base64Utils; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.security.Key; +import java.security.KeyStore; +import java.security.Provider; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.RSAPrivateKey; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +/** + * {@link JoseUtils} provides static methods JWS and JWE processing. + * + * @author tlenz + * + */ +@Slf4j +public class JoseUtils { + + /** + * Create a JWS signature. + * + *

+ * Use {@link AlgorithmIdentifiers.RSA_PSS_USING_SHA256} in case + * of a RSA based key and + * {@link AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256} + * in case of an ECC based key. + *

+ * + * @param keyStore KeyStore that should be used + * @param keyAlias Alias of the private key + * @param keyPassword Password to access the key + * @param payLoad PayLoad to sign + * @param addFullCertChain If true the full certificate chain will be + * added, otherwise only the + * X509CertSha256Fingerprint is added into JOSE + * header + * @param friendlyNameForLogging FriendlyName for the used KeyStore for logging + * purposes only + * @return Signed PayLoad in serialized form + * @throws EaafException In case of a key-access or key-usage error + * @throws JoseException In case of a JOSE error + */ + public static String createSignature(@Nonnull Pair keyStore, + @Nonnull final String keyAlias, @Nonnull final char[] keyPassword, + @Nonnull final String payLoad, boolean addFullCertChain, + @Nonnull String friendlyNameForLogging) throws EaafException, JoseException { + return createSignature(keyStore, keyAlias, keyPassword, payLoad, addFullCertChain, Collections.emptyMap(), + AlgorithmIdentifiers.RSA_PSS_USING_SHA256, AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256, + friendlyNameForLogging); + + } + + /** + * Create a JWS signature. + * + *

+ * Use {@link AlgorithmIdentifiers.RSA_PSS_USING_SHA256} in case + * of a RSA based key and + * {@link AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256} + * in case of an ECC based key. + *

+ * + * @param keyStore KeyStore that should be used + * @param keyAlias Alias of the private key + * @param keyPassword Password to access the key + * @param payLoad PayLoad to sign + * @param addFullCertChain If true the full certificate chain will be + * added, otherwise only the + * X509CertSha256Fingerprint is added into JOSE + * header + * @param joseHeaders HeaderName and HeaderValue that should be set + * into JOSE header + * @param friendlyNameForLogging FriendlyName for the used KeyStore for logging + * purposes only + * @return Signed PayLoad in serialized form + * @throws EaafException In case of a key-access or key-usage error + * @throws JoseException In case of a JOSE error + */ + public static String createSignature(@Nonnull Pair keyStore, + @Nonnull final String keyAlias, @Nonnull final char[] keyPassword, + @Nonnull final String payLoad, boolean addFullCertChain, + @Nonnull final Map joseHeaders, + @Nonnull String friendlyNameForLogging) throws EaafException, JoseException { + return createSignature(keyStore, keyAlias, keyPassword, payLoad, addFullCertChain, joseHeaders, + AlgorithmIdentifiers.RSA_PSS_USING_SHA256, AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256, + friendlyNameForLogging); + + } + + /** + * Create a JWS signature. + * + * @param keyStore KeyStore that should be used + * @param keyAlias Alias of the private key + * @param keyPassword Password to access the key + * @param payLoad PayLoad to sign + * @param addFullCertChain If true the full certificate chain will be + * added, otherwise only the + * X509CertSha256Fingerprint is added into JOSE + * header + * @param joseHeaders HeaderName and HeaderValue that should be set + * into JOSE header + * @param rsaAlgToUse Signing algorithm that should be used in case + * of a signing key based on RSA + * @param eccAlgToUse Signing algorithm that should be used in case + * of a signing key based on ECC + * @param friendlyNameForLogging FriendlyName for the used KeyStore for logging + * purposes only + * @return Signed PayLoad in serialized form + * @throws EaafException In case of a key-access or key-usage error + * @throws JoseException In case of a JOSE error + */ + public static String createSignature(@Nonnull Pair keyStore, + @Nonnull final String keyAlias, @Nonnull final char[] keyPassword, + @Nonnull final String payLoad, boolean addFullCertChain, + @Nonnull final Map joseHeaders, + @Nonnull final String rsaAlgToUse, @Nonnull final String eccAlgToUse, + @Nonnull String friendlyNameForLogging) throws EaafException, JoseException { + + final JsonWebSignature jws = new JsonWebSignature(); + + // set payload + jws.setPayload(payLoad); + + // set JOSE headers + for (final Entry el : joseHeaders.entrySet()) { + log.trace("Set JOSE header: {} with value: {} into JWS", el.getKey(), el.getValue()); + jws.setHeader(el.getKey(), el.getValue()); + + } + + // set signing information + final Pair signingCred = EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore.getFirst(), keyAlias, keyPassword, true, friendlyNameForLogging); + jws.setKey(signingCred.getFirst()); + jws.setAlgorithmHeaderValue(getKeyOperationAlgorithmFromCredential( + jws.getKey(), rsaAlgToUse, eccAlgToUse, friendlyNameForLogging)); + + // set special provider if required + if (keyStore.getSecond() != null) { + log.trace("Injecting special Java Security Provider: {}", keyStore.getSecond().getName()); + final ProviderContext providerCtx = new ProviderContext(); + providerCtx.getSuppliedKeyProviderContext().setSignatureProvider( + keyStore.getSecond().getName()); + jws.setProviderContext(providerCtx); + + } + + if (addFullCertChain) { + jws.setCertificateChainHeaderValue(signingCred.getSecond()); + + } + + jws.setX509CertSha256ThumbprintHeaderValue(signingCred.getSecond()[0]); + + return jws.getCompactSerialization(); + + } + + /** + * Verify a JOSE signature. + * + * @param serializedContent Serialized content that should be verified + * @param trustedCerts Trusted certificates that should be used for + * verification + * @param constraints {@link AlgorithmConstraints} for verification + * @return {@link JwsResult} object + * @throws JoseException In case of a signature verification error + * @throws IOException In case of a general error + */ + public static JwsResult validateSignature(@Nonnull final String serializedContent, + @Nonnull final List trustedCerts, @Nonnull final AlgorithmConstraints constraints) + throws JoseException, IOException { + final JsonWebSignature jws = new JsonWebSignature(); + // set payload + jws.setCompactSerialization(serializedContent); + + // set security constrains + jws.setAlgorithmConstraints(constraints); + + // load signinc certs + Key selectedKey = null; + final List x5cCerts = jws.getCertificateChainHeaderValue(); + final String x5t256 = jws.getX509CertSha256ThumbprintHeaderValue(); + if (x5cCerts != null) { + log.debug("Found x509 certificate in JOSE header ... "); + log.trace("Sorting received X509 certificates ... "); + final List sortedX5cCerts = X509Utils.sortCertificates(x5cCerts); + + if (trustedCerts.contains(sortedX5cCerts.get(0))) { + selectedKey = sortedX5cCerts.get(0).getPublicKey(); + + } else { + log.info("Can NOT find JOSE certificate in truststore."); + if (log.isDebugEnabled()) { + try { + log.debug("Cert: {}", Base64Utils.encodeToString(sortedX5cCerts.get(0).getEncoded())); + + } catch (final CertificateEncodingException e) { + log.warn("Can not create DEBUG output", e); + + } + } + } + + } else if (StringUtils.isNotEmpty(x5t256)) { + log.debug("Found x5t256 fingerprint in JOSE header .... "); + final X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver( + trustedCerts); + selectedKey = x509VerificationKeyResolver.resolveKey(jws, Collections.emptyList()); + + } else { + throw new JoseException("JWS contains NO signature certificate or NO certificate fingerprint"); + + } + + if (selectedKey == null) { + throw new JoseException("Can NOT select verification key for JWS. Signature verification FAILED"); + + } + + // set verification key + jws.setKey(selectedKey); + + // load payLoad + return new JwsResult( + jws.verifySignature(), + jws.getUnverifiedPayload(), + jws.getHeaders(), + x5cCerts); + + } + + /** + * Select signature algorithm for a given credential. + * + * @param key {@link X509Credential} that will be used for + * key operations + * @param rsaSigAlgorithm RSA based algorithm that should be used in case + * of RSA credential + * @param ecSigAlgorithm EC based algorithm that should be used in case + * of RSA credential + * @param friendlyNameForLogging KeyStore friendlyName for logging purposes + * @return either the RSA based algorithm or the EC based algorithm + * @throws EaafKeyUsageException In case of an unsupported private-key type + */ + private static String getKeyOperationAlgorithmFromCredential(Key key, + String rsaSigAlgorithm, String ecSigAlgorithm, String friendlyNameForLogging) + throws EaafKeyUsageException { + if (key instanceof RSAPrivateKey) { + return rsaSigAlgorithm; + + } else if (key instanceof ECPrivateKey) { + return ecSigAlgorithm; + + } else { + log.warn("Could NOT select the cryptographic algorithm from Private-Key type"); + throw new EaafKeyUsageException(EaafKeyUsageException.ERROR_CODE_01, + friendlyNameForLogging, + "Can not select cryptographic algorithm"); + + } + + } + + private JoseUtils() { + + } + + @Getter + @AllArgsConstructor + public static class JwsResult { + final boolean valid; + final String payLoad; + final Headers fullJoseHeader; + final List x5cCerts; + + } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/SZR_v4.0.wsdl b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/SZR_v4.0.wsdl new file mode 100644 index 00000000..e7f296bd --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/SZR_v4.0.wsdl @@ -0,0 +1,441 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/pvp19.xsd b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/pvp19.xsd new file mode 100644 index 00000000..596a2b99 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/pvp19.xsd @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + additional authentication properties + + + + + + + + + + + + + + + + + + + + + + + additional authorization properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + additional principal attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_ecdsa.xsd b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_ecdsa.xsd new file mode 100644 index 00000000..87ee80be --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_ecdsa.xsd @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_persondata.xsd b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_persondata.xsd new file mode 100644 index 00000000..3c9ac932 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_persondata.xsd @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_pvp_sec.xsd b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_pvp_sec.xsd new file mode 100644 index 00000000..5001c1b8 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_pvp_sec.xsd @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-schemas.xml b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-schemas.xml new file mode 100644 index 00000000..d40efa45 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-schemas.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-wsdl.xml b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-wsdl.xml new file mode 100644 index 00000000..f95c35f0 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0-wsdl.xml @@ -0,0 +1,10 @@ + + + + false + + + \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0.xsd b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0.xsd new file mode 100644 index 00000000..2d25f2dc --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_v4.0.xsd @@ -0,0 +1,443 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_xmldsig.xsd b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_xmldsig.xsd new file mode 100644 index 00000000..96b50b40 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/szr_client/szr_xmldsig.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index fca548b7..d9275089 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -19,17 +19,20 @@ * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.when; import java.io.IOException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchProviderException; +import java.util.Arrays; +import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @@ -37,6 +40,7 @@ import javax.xml.bind.Unmarshaller; import javax.xml.parsers.ParserConfigurationException; import javax.xml.ws.soap.SOAPFaultException; +import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.cxf.binding.soap.SoapFault; import org.junit.Assert; @@ -70,12 +74,7 @@ import at.gv.egiz.eaaf.core.exceptions.EaafParserException; import at.gv.egiz.eaaf.core.impl.data.Triple; import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; import at.gv.egiz.eaaf.core.impl.utils.DomUtils; -import szrservices.GetIdentityLinkEidasResponse; -import szrservices.IdentityLinkType; -import szrservices.PersonInfoType; -import szrservices.SZR; -import szrservices.SZRException_Exception; -import szrservices.TravelDocumentType; +import szrservices.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_tasks_test.xml") @@ -91,12 +90,11 @@ public class SzrClientTest { private static final String familyName = "Mustermann"; private static final String dateOfBirth = "1989-05-05"; private static final String eIDASeID = "IS/AT/1234sdgsdfg56789ABCDEF"; - private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; /** * jUnit class initializer. - * + * * @throws IOException In case of an error */ @BeforeClass @@ -109,6 +107,49 @@ public class SzrClientTest { @Rule public SoapServiceRule soap = SoapServiceRule.newInstance(); + + + @Test +public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception { + SZR szrMock = soap.mock(SZR.class, "hhttp://localhost:1234/demoszr"); + + final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); + final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); + szrResponse.getOut().add(result1); + + when(szrMock.getBPKFromStammzahlEncrypted(anyList())) + .thenReturn(Arrays.asList(result1)); + +// szrMock.getStammzahlEncrypted() TODO ??? + } + + @Test + public void getBcBindValid() throws SZRException_Exception, SzrCommunicationException { + SZR szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); + + final SignContentResponse szrResponse = new SignContentResponse(); + final SignContentEntry result1 = new SignContentEntry(); + final SignContentResponseType content = new SignContentResponseType(); + content.getOut().add(result1); + szrResponse.setSignContentResponse(content); + + result1.setKey("bcBindReq"); + result1.setValue(RandomStringUtils.randomAlphanumeric(100)); + + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); + + final String bcBind = szrClient.getBcBind( + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10)); + + Assert.assertNotNull("bcBind is null", bcBind); + Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); + + + } + + @Test public void getIdentityLinkRawModeValidResponse() throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException, JAXBException { @@ -164,7 +205,7 @@ public class SzrClientTest { checkElement("p344:F455", ((SOAPFaultException) e.getCause()).getFault().getFaultCode()); checkElement( "The travel document you sent to insert a person already exists for another person. " - + "Either check the document or have the person altered accordingly", + + "Either check the document or have the person altered accordingly", ((SOAPFaultException) e.getCause()).getFault().getFaultString()); } @@ -174,13 +215,18 @@ public class SzrClientTest { @Ignore @Test public void getBpkTest() throws SZRException_Exception, EidasSAuthenticationException { - final String bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, + final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, basicConfig.getBasicConfiguration( Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")); - if (StringUtils.isEmpty(bPK)) { - throw new SzrCommunicationException("ernb.01", new Object[] { "bPK is null or empty" }); + if (bPK.isEmpty()) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); + } + for (String b : bPK) { + if (StringUtils.isEmpty(b)) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); + } } } @@ -217,7 +263,7 @@ public class SzrClientTest { final javax.xml.namespace.QName qName = new javax.xml.namespace.QName("urn:SZRServices", "F455", "p344"); final SoapFault fault = new SoapFault( "The travel document you sent to insert a person already exists for another person. " - + "Either check the document or have the person altered accordingly", + + "Either check the document or have the person altered accordingly", qName); fault.setRole("urn:SZRServices"); fault.setDetail(detailerror); @@ -233,7 +279,7 @@ public class SzrClientTest { return hashBase64; } catch (final Exception ex) { - throw new EidasSAuthenticationException("internal.03", new Object[] {}, ex); + throw new EidasSAuthenticationException("internal.03", new Object[]{}, ex); } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index 2f6a989e..a30ea2a0 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -27,6 +27,7 @@ import java.io.IOException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchProviderException; +import java.util.List; import org.apache.commons.lang3.StringUtils; import org.junit.Ignore; @@ -132,13 +133,18 @@ public class SzrClientTestProduction { @Ignore @Test public void getBpkTest() throws SZRException_Exception, EidasSAuthenticationException { - final String bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, + final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, basicConfig.getBasicConfiguration( Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")); - if (StringUtils.isEmpty(bPK)) { - throw new SzrCommunicationException("ernb.01", new Object[] { "bPK is null or empty" }); + if (bPK.isEmpty()) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); + } + for (String b : bPK) { + if (StringUtils.isEmpty(b)) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); + } } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java new file mode 100644 index 00000000..6eeb437d --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java @@ -0,0 +1,119 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummySpecificCommunicationService; +import at.gv.e_government.reference.namespace.persondata._20020228.PostalAddressType; +import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import com.google.common.collect.ImmutableMap; +import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; +import lombok.val; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.spy; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/SpringTest-context_tasks_test.xml") +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +@PrepareForTest(CreateIdentityLinkTask.class) +public class CreateIdentityLinkTaskEidNewSimpleTest { + + + @Autowired(required = true) + private CreateIdentityLinkTask task; + @Autowired(required = true) + private DummySpecificCommunicationService commService; + @Autowired(required = true) + private IConfiguration basicConfig; + @Autowired + protected EidasAttributeRegistry attrRegistry; + + final ExecutionContext executionContext = new ExecutionContextImpl(); + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private TestRequestImpl pendingReq; + private DummySpConfiguration oaParam; + + /** + * jUnit class initializer. + * + * @throws IOException In case of an error + */ + @BeforeClass + public static void classInitializer() throws IOException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/junit_config_3.properties"); + + } + + /** + * jUnit test set-up. + */ + @Before + public void setUp() throws EaafStorageException { + + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + final Map spConfig = new HashMap<>(); + spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); + spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); + oaParam = new DummySpConfiguration(spConfig, basicConfig); + pendingReq = new TestRequestImpl(); + val b = new AuthenticationResponse.Builder(); + val response = b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf").build(); + + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + pendingReq.setSpConfig(oaParam); + pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); + pendingReq.setAuthUrl("http://test.com/"); + + executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "XX"); + } + + @Test + public void getPkFromKeystoreTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + + Method method = CreateIdentityLinkTask.class.getDeclaredMethod("getPkFromKeystore"); + method.setAccessible(true); + String returnValue = (String) method.invoke(task); + } +} + + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java new file mode 100644 index 00000000..185181dd --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -0,0 +1,217 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeEidProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateAuthnRequestTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummySpecificCommunicationService; +import at.gv.e_government.reference.namespace.persondata._20020228.PostalAddressType; +import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSortedSet; +import com.google.common.collect.Maps; +import com.skjolberg.mockito.soap.SoapServiceRule; +import eu.eidas.auth.commons.EIDASStatusCode; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.AttributeValueMarshaller; +import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; +import eu.eidas.auth.commons.attribute.PersonType; +import eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller; +import eu.eidas.auth.commons.attribute.impl.StringAttributeValueMarshaller; +import eu.eidas.auth.commons.light.ILightRequest; +import eu.eidas.auth.commons.light.ILightResponse; +import eu.eidas.auth.commons.light.impl.LightRequest; +import eu.eidas.auth.commons.light.impl.LightResponse; +import eu.eidas.auth.commons.light.impl.ResponseStatus; +import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; +import eu.eidas.specificcommunication.exception.SpecificCommunicationException; +import lombok.val; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.internal.builders.JUnit3Builder; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import szrservices.SZR; +import szrservices.SZRException_Exception; + +import javax.xml.namespace.QName; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import static org.mockito.ArgumentMatchers.any; +import static org.powermock.api.mockito.PowerMockito.*; + +@RunWith(SpringJUnit4ClassRunner.class) +//@RunWith(PowerMockRunner.class) +//@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) +@PrepareForTest(CreateIdentityLinkTask.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +@ContextConfiguration("/SpringTest-context_tasks_test.xml") +public class CreateIdentityLinkTaskEidNewTest { + + + @Autowired(required = true) + private CreateIdentityLinkTask task; + @Autowired(required = true) + private DummySpecificCommunicationService commService; + @Autowired(required = true) + private IConfiguration basicConfig; + @Autowired + protected EidasAttributeRegistry attrRegistry; + + final ExecutionContext executionContext = new ExecutionContextImpl(); + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private TestRequestImpl pendingReq; + private DummySpConfiguration oaParam; + private SZR szrMock; + final SoapServiceRule soap = SoapServiceRule.newInstance(); + + /** + * jUnit class initializer. + * + * @throws IOException In case of an error + */ + @BeforeClass + public static void classInitializer() throws IOException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/junit_config_3.properties"); + + } + + /** + * jUnit test set-up. + */ + @Before + public void setUp() throws EaafStorageException, URISyntaxException { + + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + final Map spConfig = new HashMap<>(); + spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); + spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); + spConfig.put("eidMode", "new"); + oaParam = new DummySpConfiguration(spConfig, basicConfig); + pendingReq = new TestRequestImpl(); + + AuthenticationResponse response = buildDummyAuthResponse(); + + + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + pendingReq.setSpConfig(oaParam); + pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); + pendingReq.setAuthUrl("http://test.com/"); + + executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "XX"); + + szrMock = soap.mock(SZR.class, "http://localhost:2526/szrService"); + } + + @NotNull + private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { + AttributeDefinition attributeDef = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER) + .nameUri(new URI("ad", "sd", "ff")).personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "af")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + AttributeDefinition attributeDef2 = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME) + .nameUri(new URI("ad", "sd", "fff")).personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "aff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + AttributeDefinition attributeDef3 = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME) + .nameUri(new URI("ad", "sd", "ffff")).personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "afff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + AttributeDefinition attributeDef4 = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH) + .nameUri(new URI("ad", "sd", "fffff")).personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "affff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); + + ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder().put(attributeDef, "de/st/" + RandomStringUtils.randomNumeric(64)) + .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) + .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)) + .put(attributeDef4, "2001-01-01") + .build(); + + + val b = new AuthenticationResponse.Builder(); + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf") + .subjectNameIdFormat("afaf").attributes(attributeMap).build(); + } + + @Test(expected = RuntimeException.class) + public void firstTest() { + // keystore password f/+saJBc3a}*/T^s + try { + + SZR szrMock2 = Mockito.mock(SZR.class, Mockito.CALLS_REAL_METHODS); +// when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); + when(szrMock2, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); + // Wie kann ich das vom Bean rein gehängte SZR mit dem Mock überschreiben? + + task.execute(pendingReq, executionContext); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(); + } + +// val spyTask = spy(task); +// Map requiredAttributes = new HashMap<>(); +// requiredAttributes.put(Constants.eIDAS_ATTR_PERSONALIDENTIFIER, "asdf"); +// requiredAttributes.put(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, "asdf"); +// requiredAttributes.put(Constants.eIDAS_ATTR_CURRENTGIVENNAME, "asdf"); +// requiredAttributes.put(Constants.eIDAS_ATTR_DATEOFBIRTH, new DateTime()); +// requiredAttributes.put(Constants.eIDAS_ATTR_PLACEOFBIRTH, "adf"); +// requiredAttributes.put(Constants.eIDAS_ATTR_BIRTHNAME, "adf"); +// requiredAttributes.put(Constants.eIDAS_ATTR_CURRENTADDRESS, new PostalAddressType()); +// try { +// doReturn(requiredAttributes).when(spyTask, "convertEidasAttrToSimpleMap", (any(ImmutableMap.class))); +// spyTask.execute(pendingReq, executionContext); +// } catch (final Exception e) { +// e.printStackTrace(); +// Assert.fail(); +// } + } + +} + + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties new file mode 100644 index 00000000..326e14fe --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties @@ -0,0 +1,109 @@ +## Basic service configuration +eidas.ms.context.url.prefix= +eidas.ms.context.url.request.validation=false + +eidas.ms.context.use.clustermode=true + +##Monitoring +eidas.ms.monitoring.eIDASNode.metadata.url= + + +##Specific logger configuration +eidas.ms.technicallog.write.MDS.into.techlog=true +eidas.ms.revisionlog.write.MDS.into.revisionlog=true +eidas.ms.revisionlog.logIPAddressOfUser=true + +##Directory for static Web content +eidas.ms.webcontent.static.directory=webcontent/ +eidas.ms.webcontent.templates=templates/ +eidas.ms.webcontent.properties=properties/messages + +## extended validation of pending-request Id's +eidas.ms.core.pendingrequestid.maxlifetime=300 +eidas.ms.core.pendingrequestid.digist.algorithm=HmacSHA256 +eidas.ms.core.pendingrequestid.digist.secret=pendingReqIdSecret + +## eIDAS Ref. Implementation connector ### +eidas.ms.auth.eIDAS.node_v2.entityId=ownSpecificConnector +eidas.ms.auth.eIDAS.node_v2.forward.endpoint=http://test.com/ +eidas.ms.auth.eIDAS.node_v2.forward.method=POST +eidas.ms.auth.eIDAS.node_v2.countrycode=AT +eidas.ms.auth.eIDAS.node_v2.publicSectorTargets=.* +eidas.ms.auth.eIDAS.node_v2.workarounds.addAlwaysProviderName=true +eidas.ms.auth.eIDAS.node_v2.workarounds.useRequestIdAsTransactionIdentifier=true +eidas.ms.auth.eIDAS.node_v2.workarounds.useStaticProviderNameForPublicSPs=true +eidas.ms.auth.eIDAS.node_v2.staticProviderNameForPublicSPs=myNode + +eidas.ms.auth.eIDAS.node_v2.loa.requested.minimum=http://eidas.europa.eu/LoA/high + +eidas.ms.auth.eIDAS.szrclient.useTestService=true +eidas.ms.auth.eIDAS.szrclient.endpoint.prod= +eidas.ms.auth.eIDAS.szrclient.endpoint.test=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.szrclient.ssl.keyStore.path=keys/..... +eidas.ms.auth.eIDAS.szrclient.ssl.keyStore.password= +eidas.ms.auth.eIDAS.szrclient.ssl.trustStore.path= +eidas.ms.auth.eIDAS.szrclient.ssl.trustStore.password= +eidas.ms.auth.eIDAS.szrclient.timeout.connection=15 +eidas.ms.auth.eIDAS.szrclient.timeout.response=30 +eidas.ms.auth.eIDAS.szrclient.params.vkz= + +eidas.ms.auth.eIDAS.szrclient.params.useSZRForbPKCalculation=false + + +#Raw eIDAS Id data storage +eidas.ms.auth.eIDAS.szrclient.workarounds.eidmapping.revisionlog.active=true + +eidas.ms.auth.eIDAS.szrclient.params.setPlaceOfBirthIfAvailable=true +eidas.ms.auth.eIDAS.szrclient.params.setBirthNameIfAvailable=true + +eidas.ms.auth.eIDAS.szrclient.debug.logfullmessages=true +eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution=false + +##without mandates +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.0=PersonIdentifier,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.1=FamilyName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.2=FirstName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.3=DateOfBirth,true + +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.4=PlaceOfBirth,false +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.5=BirthName,false +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.6=Gender,false +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.7=CurrentAddress,false +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.8=testtest,false + +##with mandates ---- NOT FULLY SUPPORTED AT THE MOMENT ----- +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.0=PersonIdentifier,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.1=FamilyName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.2=FirstName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.3=DateOfBirth,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.4=LegalPerson,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true + + +## PVP2 S-Profile end-point configuration +eidas.ms.pvp2.keystore.path=keys/..... +eidas.ms.pvp2.keystore.password= +eidas.ms.pvp2.key.metadata.alias= +eidas.ms.pvp2.key.metadata.password= +eidas.ms.pvp2.key.signing.alias= +eidas.ms.pvp2.key.signing.password= +eidas.ms.pvp2.metadata.validity=24 + +## Service Provider configuration +eidas.ms.sp.0.uniqueID= +eidas.ms.sp.0.pvp2.metadata.truststore= +eidas.ms.sp.0.pvp2.metadata.truststore.password= +eidas.ms.sp.0.eidMode=new + +#eidas.ms.sp.0.friendlyName= +#eidas.ms.sp.0.pvp2.metadata.url= +#eidas.ms.sp.0.policy.allowed.requested.targets=.* +#eidas.ms.sp.0.policy.hasBaseIdTransferRestriction=false + + +##only for advanced config +eidas.ms.configuration.sp.disableRegistrationRequirement= +eidas.ms.configuration.restrictions.baseID.spTransmission= +eidas.ms.configuration.auth.default.countrycode= +eidas.ms.configuration.pvp.scheme.validation= +eidas.ms.configuration.pvp.enable.entitycategories= \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/teststore.jks b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/teststore.jks new file mode 100644 index 00000000..fcc6400c Binary files /dev/null and b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/teststore.jks differ -- cgit v1.2.3 From 3332e8c363b624e7478f303c403ea709844e822f Mon Sep 17 00:00:00 2001 From: lalber Date: Tue, 20 Oct 2020 09:02:39 +0200 Subject: fixes thanks to Thomas --- eidas_modules/authmodule-eIDAS-v2/pom.xml | 6 ------ .../modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java | 7 +++++-- .../eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java | 11 +++++++---- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/eidas_modules/authmodule-eIDAS-v2/pom.xml b/eidas_modules/authmodule-eIDAS-v2/pom.xml index 7bbdaf78..4fe2bb36 100644 --- a/eidas_modules/authmodule-eIDAS-v2/pom.xml +++ b/eidas_modules/authmodule-eIDAS-v2/pom.xml @@ -160,12 +160,6 @@ 2.0.7 test - - eu.eidas - eidas-light-commons - 2.4.0 - test - at.gv.egiz.eaaf eaaf_core_utils diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index e4a22cbc..93813ff5 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -95,6 +95,9 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { @Autowired private ICcSpecificEidProcessingService eidPostProcessor; + @Autowired + EaafKeyStoreFactory keyStoreFactory; + /* * (non-Javadoc) * @@ -331,14 +334,14 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } private String getPkFromKeystore() throws EaafException, KeyStoreException { - EaafKeyStoreFactory keyStoreFactory = new EaafKeyStoreFactory(); KeyStoreConfiguration configuration = new KeyStoreConfiguration(); final String current = new java.io.File(".").toURI().toString(); configuration.setSoftKeyStoreFilePath(current + "src/test/resources/keystore/teststore.jks"); - configuration.setSoftKeyStorePassword("f/+saJBc3a}*/T^s"); configuration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.JKS); + configuration.setFriendlyName("connectorkeypair"); + configuration.setKeyStoreName("connectorkeypair"); val ks = keyStoreFactory.buildNewKeyStore(configuration); val publicKey = ks.getFirst().getCertificate("connectorkeypair").getPublicKey(); return Base64.getEncoder().encodeToString(publicKey.getEncoded()); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index 185181dd..f674b6b1 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -63,6 +63,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import szrservices.PersonInfoType; import szrservices.SZR; import szrservices.SZRException_Exception; @@ -144,7 +145,7 @@ public class CreateIdentityLinkTaskEidNewTest { executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "XX"); - szrMock = soap.mock(SZR.class, "http://localhost:2526/szrService"); + szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); } @NotNull @@ -183,9 +184,11 @@ public class CreateIdentityLinkTaskEidNewTest { // keystore password f/+saJBc3a}*/T^s try { - SZR szrMock2 = Mockito.mock(SZR.class, Mockito.CALLS_REAL_METHODS); -// when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); - when(szrMock2, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); + String test = szrMock.getStammzahlEncrypted(new PersonInfoType(), false); + +// SZR szrMock2 = Mockito.mock(SZR.class, Mockito.CALLS_REAL_METHODS); + when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); +// when(szrMock2, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); // Wie kann ich das vom Bean rein gehängte SZR mit dem Mock überschreiben? task.execute(pendingReq, executionContext); -- cgit v1.2.3 From d42ef2bccc0acd4e1ee830f42956a5cafb863299 Mon Sep 17 00:00:00 2001 From: lalber Date: Tue, 20 Oct 2020 16:57:45 +0200 Subject: cyclic depend --- eidas_modules/authmodule-eIDAS-v2/pom.xml | 6 ++ .../specific/modules/auth/eidas/v2/Constants.java | 5 ++ .../eidas/v2/tasks/CreateIdentityLinkTask.java | 98 ++++++++++++---------- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 21 +++-- .../resources/SpringTest-context_tasks_test_2.xml | 77 +++++++++++++++++ 5 files changed, 160 insertions(+), 47 deletions(-) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml diff --git a/eidas_modules/authmodule-eIDAS-v2/pom.xml b/eidas_modules/authmodule-eIDAS-v2/pom.xml index 4fe2bb36..9eeb0994 100644 --- a/eidas_modules/authmodule-eIDAS-v2/pom.xml +++ b/eidas_modules/authmodule-eIDAS-v2/pom.xml @@ -183,6 +183,12 @@ jose4j 0.7.2 + + at.asitplus.eidas.ms_specific + ms_specific_connector + 1.1.1-SNAPSHOT + test + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java index 3eec12bd..eac62aae 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java @@ -156,6 +156,11 @@ public class Constants { // Default values for SZR communication public static final String SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE = "ELEKTR_DOKUMENT"; + // AuthBlock + public static final String SZR_AUTHBLOCK = "AUTHBLOCK"; + public static final String EIDAS_BIND = "EIDAS_BIND"; + + // TODO remove!!! public static final String SZR_CONSTANTS_DEFAULT_ISSUING_DATE = "2014-01-01"; public static final String SZR_CONSTANTS_DEFAULT_ISSUING_AUTHORITY = "ms-specific eIDAS-Node for AT"; diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index 93813ff5..b141402a 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -32,6 +32,7 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicati import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.ICcSpecificEidProcessingService; import at.asitplus.eidas.specific.modules.auth.eidas.v2.szr.SzrClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.EidasResponseUtils; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.JoseUtils; import at.gv.e_government.reference.namespace.persondata._20020228.AlternativeNameType; import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType; @@ -61,6 +62,7 @@ import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; +import org.bouncycastle.jce.PKCS10CertificationRequest; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -72,8 +74,10 @@ import szrservices.TravelDocumentType; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.InputStream; +import java.io.*; +import java.security.KeyStore; import java.security.KeyStoreException; +import java.security.Provider; import java.util.Base64; import java.util.HashMap; import java.util.List; @@ -98,6 +102,10 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { @Autowired EaafKeyStoreFactory keyStoreFactory; + Pair ks; + private final String KSPASSWORD = "f/+saJBc3a}*/T^s"; + private final String KSALIAS = "connectorkeypair"; + /* * (non-Javadoc) * @@ -114,6 +122,9 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); final ILightResponse eidasResponse = authProcessData.getGenericDataFromSession( Constants.DATA_FULL_EIDAS_RESPONSE, ILightResponse.class); + String eidMode = pendingReq.getServiceProviderConfiguration() + .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); + final Map simpleAttrMap = convertEidasAttrToSimpleMap(eidasResponse.getAttributes() .getAttributeMap()); @@ -222,7 +233,6 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - String eidMode = pendingReq.getServiceProviderConfiguration().getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); if (eidMode.equals("new")) { String vsz = szrClient.getEncryptedStammzahl(personInfo); @@ -239,8 +249,10 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { ObjectMapper mapper = new ObjectMapper(); String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); -// JoseUtils.createSignature(new Pair<>(ks, ks.getProvider()), "connectorkeypair", passord.chararray(), jwsPayload, false, ); //TODO joseutils kopiern + String jwsSignature = JoseUtils.createSignature(ks, KSALIAS, KSPASSWORD.toCharArray(), jwsPayload, false, KSALIAS);//TODO joseutils kopiern + authProcessData.setGenericDataToSession(Constants.SZR_AUTHBLOCK, jwsSignature); + authProcessData.setGenericDataToSession(Constants.EIDAS_BIND, jwsSignature); } else { final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(personInfo); @@ -282,44 +294,46 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - if (identityLink == null) { - log.error("ERnB did not return an identity link."); - throw new SzrCommunicationException("ernb.00", null); + if (eidMode.equals("new")) {} + else { + if (identityLink == null) { + log.error("ERnB did not return an identity link."); + throw new SzrCommunicationException("ernb.00", null); - } - revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_IDL_RECEIVED, - identityLink.getSamlAssertion().getAttribute(SimpleIdentityLinkAssertionParser.ASSERTIONID)); + } + revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_IDL_RECEIVED, + identityLink.getSamlAssertion().getAttribute(SimpleIdentityLinkAssertionParser.ASSERTIONID)); - if (bpk == null) { - log.error("ERnB did not return a bPK for target: " + pendingReq.getServiceProviderConfiguration() - .getAreaSpecificTargetIdentifier()); - throw new SzrCommunicationException("ernb.01", null); + if (bpk == null) { + log.error("ERnB did not return a bPK for target: " + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); + throw new SzrCommunicationException("ernb.01", null); - } - revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_BPK_RECEIVED); - - log.debug("ERnB communication was successfull"); - - authProcessData.setForeigner(true); - authProcessData.setIdentityLink(identityLink); - authProcessData.setGenericDataToSession( - PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, - EidasResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get( - Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); - - // set bPK and bPKType into auth session - authProcessData.setGenericDataToSession( - PvpAttributeDefinitions.BPK_NAME, - extendBpkByPrefix( - bpk, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier())); - authProcessData.setGenericDataToSession( - PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); - - // store pending-request - requestStoreage.storePendingRequest(pendingReq); + } + revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_BPK_RECEIVED); + + log.debug("ERnB communication was successfull"); + + authProcessData.setForeigner(true); + authProcessData.setIdentityLink(identityLink); + authProcessData.setGenericDataToSession( + PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, + EidasResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get( + Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); + + // set bPK and bPKType into auth session + authProcessData.setGenericDataToSession( + PvpAttributeDefinitions.BPK_NAME, + extendBpkByPrefix( + bpk, + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier())); + authProcessData.setGenericDataToSession( + PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + // store pending-request + requestStoreage.storePendingRequest(pendingReq); + } } catch (final EidasAttributeException e) { throw new TaskExecutionException(pendingReq, "Minimum required eIDAS attributeset not found.", e); @@ -338,12 +352,12 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { final String current = new java.io.File(".").toURI().toString(); configuration.setSoftKeyStoreFilePath(current + "src/test/resources/keystore/teststore.jks"); - configuration.setSoftKeyStorePassword("f/+saJBc3a}*/T^s"); + configuration.setSoftKeyStorePassword(KSPASSWORD); //TODO from config configuration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.JKS); - configuration.setFriendlyName("connectorkeypair"); - configuration.setKeyStoreName("connectorkeypair"); - val ks = keyStoreFactory.buildNewKeyStore(configuration); - val publicKey = ks.getFirst().getCertificate("connectorkeypair").getPublicKey(); + configuration.setFriendlyName(KSALIAS); + configuration.setKeyStoreName(KSALIAS); + ks = keyStoreFactory.buildNewKeyStore(configuration); + val publicKey = ks.getFirst().getCertificate(KSALIAS).getPublicKey(); return Base64.getEncoder().encodeToString(publicKey.getEncoded()); } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index f674b6b1..028210cb 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -9,6 +9,7 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateAuthnReque import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummySpecificCommunicationService; import at.gv.e_government.reference.namespace.persondata._20020228.PostalAddressType; import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; @@ -16,6 +17,7 @@ import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.controller.tasks.FinalizeAuthenticationTask; import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; @@ -63,9 +65,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import szrservices.PersonInfoType; -import szrservices.SZR; -import szrservices.SZRException_Exception; +import szrservices.*; import javax.xml.namespace.QName; import java.io.IOException; @@ -83,13 +83,15 @@ import static org.powermock.api.mockito.PowerMockito.*; //@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) @PrepareForTest(CreateIdentityLinkTask.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) -@ContextConfiguration("/SpringTest-context_tasks_test.xml") +@ContextConfiguration("/SpringTest-context_tasks_test_2.xml") public class CreateIdentityLinkTaskEidNewTest { @Autowired(required = true) private CreateIdentityLinkTask task; @Autowired(required = true) + private FinalizeAuthenticationTask authTask; + @Autowired(required = true) private DummySpecificCommunicationService commService; @Autowired(required = true) private IConfiguration basicConfig; @@ -142,8 +144,10 @@ public class CreateIdentityLinkTaskEidNewTest { pendingReq.setSpConfig(oaParam); pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); pendingReq.setAuthUrl("http://test.com/"); + pendingReq.setTransactionId("avaasbav"); executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "XX"); + executionContext.put(EaafConstants.PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT, true); szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); } @@ -179,7 +183,7 @@ public class CreateIdentityLinkTaskEidNewTest { .subjectNameIdFormat("afaf").attributes(attributeMap).build(); } - @Test(expected = RuntimeException.class) + @Test public void firstTest() { // keystore password f/+saJBc3a}*/T^s try { @@ -188,10 +192,17 @@ public class CreateIdentityLinkTaskEidNewTest { // SZR szrMock2 = Mockito.mock(SZR.class, Mockito.CALLS_REAL_METHODS); when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); + val signContentResp = new SignContentResponseType(); + SignContentEntry signContentEntry = new SignContentEntry(); + signContentEntry.setValue(RandomStringUtils.randomAlphanumeric(10)); + signContentResp.getOut().add(signContentEntry); + when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); // when(szrMock2, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); // Wie kann ich das vom Bean rein gehängte SZR mit dem Mock überschreiben? task.execute(pendingReq, executionContext); + + authTask.execute(pendingReq, executionContext); } catch (Exception e) { e.printStackTrace(); Assert.fail(); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml new file mode 100644 index 00000000..93b12a7c --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- cgit v1.2.3 From 608b9ac7a9f4d3ebdb6efa2d4e5453d5a015be3a Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 21 Oct 2020 11:23:40 +0200 Subject: fix --- eidas_modules/authmodule-eIDAS-v2/pom.xml | 6 -- .../CreateIdentityLinkTaskEidNewSimpleTest.java | 119 --------------------- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 10 +- .../resources/SpringTest-context_tasks_test_2.xml | 77 ------------- 4 files changed, 5 insertions(+), 207 deletions(-) delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml diff --git a/eidas_modules/authmodule-eIDAS-v2/pom.xml b/eidas_modules/authmodule-eIDAS-v2/pom.xml index 9eeb0994..4fe2bb36 100644 --- a/eidas_modules/authmodule-eIDAS-v2/pom.xml +++ b/eidas_modules/authmodule-eIDAS-v2/pom.xml @@ -183,12 +183,6 @@ jose4j 0.7.2 - - at.asitplus.eidas.ms_specific - ms_specific_connector - 1.1.1-SNAPSHOT - test - diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java deleted file mode 100644 index 6eeb437d..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewSimpleTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; - -import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummySpecificCommunicationService; -import at.gv.e_government.reference.namespace.persondata._20020228.PostalAddressType; -import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; -import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; -import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; -import com.google.common.collect.ImmutableMap; -import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; -import lombok.val; -import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.ArgumentMatchers.any; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.spy; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("/SpringTest-context_tasks_test.xml") -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) -@PrepareForTest(CreateIdentityLinkTask.class) -public class CreateIdentityLinkTaskEidNewSimpleTest { - - - @Autowired(required = true) - private CreateIdentityLinkTask task; - @Autowired(required = true) - private DummySpecificCommunicationService commService; - @Autowired(required = true) - private IConfiguration basicConfig; - @Autowired - protected EidasAttributeRegistry attrRegistry; - - final ExecutionContext executionContext = new ExecutionContextImpl(); - private MockHttpServletRequest httpReq; - private MockHttpServletResponse httpResp; - private TestRequestImpl pendingReq; - private DummySpConfiguration oaParam; - - /** - * jUnit class initializer. - * - * @throws IOException In case of an error - */ - @BeforeClass - public static void classInitializer() throws IOException { - final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current - + "src/test/resources/config/junit_config_3.properties"); - - } - - /** - * jUnit test set-up. - */ - @Before - public void setUp() throws EaafStorageException { - - httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); - httpResp = new MockHttpServletResponse(); - RequestContextHolder.resetRequestAttributes(); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - - final Map spConfig = new HashMap<>(); - spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); - spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); - oaParam = new DummySpConfiguration(spConfig, basicConfig); - pendingReq = new TestRequestImpl(); - val b = new AuthenticationResponse.Builder(); - val response = b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf").build(); - - pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - pendingReq.setSpConfig(oaParam); - pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); - pendingReq.setAuthUrl("http://test.com/"); - - executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "XX"); - } - - @Test - public void getPkFromKeystoreTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { - - Method method = CreateIdentityLinkTask.class.getDeclaredMethod("getPkFromKeystore"); - method.setAccessible(true); - String returnValue = (String) method.invoke(task); - } -} - - diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index 028210cb..7a214744 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -83,14 +83,14 @@ import static org.powermock.api.mockito.PowerMockito.*; //@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) @PrepareForTest(CreateIdentityLinkTask.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) -@ContextConfiguration("/SpringTest-context_tasks_test_2.xml") +@ContextConfiguration("/SpringTest-context_tasks_test.xml") public class CreateIdentityLinkTaskEidNewTest { @Autowired(required = true) private CreateIdentityLinkTask task; - @Autowired(required = true) - private FinalizeAuthenticationTask authTask; +// @Autowired(required = true) +// private FinalizeAuthenticationTask authTask; @Autowired(required = true) private DummySpecificCommunicationService commService; @Autowired(required = true) @@ -184,7 +184,7 @@ public class CreateIdentityLinkTaskEidNewTest { } @Test - public void firstTest() { + public void fullTest() { // keystore password f/+saJBc3a}*/T^s try { @@ -202,7 +202,7 @@ public class CreateIdentityLinkTaskEidNewTest { task.execute(pendingReq, executionContext); - authTask.execute(pendingReq, executionContext); +// authTask.execute(pendingReq, executionContext); } catch (Exception e) { e.printStackTrace(); Assert.fail(); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml deleted file mode 100644 index 93b12a7c..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test_2.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file -- cgit v1.2.3 From 8e239b9cb072e62d693f3d54a6a9ad2d9983cc71 Mon Sep 17 00:00:00 2001 From: lalber Date: Mon, 2 Nov 2020 23:29:54 +0100 Subject: AuthDataBuilder and AttributeBuilder --- .../attributes/AuthBlockAttributeBuilder.java | 64 ++++++++++ .../attributes/EidasBindAttributeBuilder.java | 64 ++++++++++ .../builder/AuthenticationDataBuilder.java | 37 +++--- .../at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder | 2 + .../main/resources/SpringTest_connector.beans.xml | 129 +++++++++++++++++++++ .../test/AuthenticationDataBuilderTest.java | 95 +++++++++++++++ .../resources/config/junit_config_3.properties | 115 ++++++++++++++++++ .../specific/modules/auth/eidas/v2/Constants.java | 4 +- .../eidas/v2/tasks/CreateIdentityLinkTask.java | 13 ++- 9 files changed, 503 insertions(+), 20 deletions(-) create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java create mode 100644 connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder create mode 100644 connector/src/main/resources/SpringTest_connector.beans.xml create mode 100644 connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java create mode 100644 connector/src/test/resources/config/junit_config_3.properties diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java new file mode 100644 index 00000000..ab5db0a6 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.asitplus.eidas.specific.connector.attributes; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +@PvpMetadata +public class AuthBlockAttributeBuilder implements IPvpAttributeBuilder { + + private static final String AUTHBLOCK_FRIENDLY_NAME = "AUTHBLOCK"; + private static final String AUTHBLOCK_NAME = "urn:oid:x.x.x.x"; //TODO set oid + + @Override + public String getName() { + return AUTHBLOCK_NAME; + } + + @Override + public ATT build(final ISpConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + String authBlock = authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class); + if (authBlock != null) { + return g.buildStringAttribute(AUTHBLOCK_FRIENDLY_NAME, AUTHBLOCK_NAME, authBlock); + + } else { + throw new UnavailableAttributeException(AUTHBLOCK_NAME); + } + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(AUTHBLOCK_FRIENDLY_NAME, AUTHBLOCK_NAME); + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java new file mode 100644 index 00000000..c6dfed1a --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.asitplus.eidas.specific.connector.attributes; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +@PvpMetadata +public class EidasBindAttributeBuilder implements IPvpAttributeBuilder { + + private static final String EIDASBIND_FRIENDLY_NAME = "EIDASBIND"; + private static final String EIDASBIND_NAME = "urn:oid:x.x.x.x"; //TODO set oid + + @Override + public String getName() { + return EIDASBIND_NAME; + } + + @Override + public ATT build(final ISpConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + String eidasBind = authData.getGenericData(Constants.EIDAS_BIND, String.class); + if (eidasBind != null) { + return g.buildStringAttribute(EIDASBIND_FRIENDLY_NAME, EIDASBIND_NAME, eidasBind); + + } else { + throw new UnavailableAttributeException(EIDASBIND_NAME); + } + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EIDASBIND_FRIENDLY_NAME, EIDASBIND_NAME); + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java index b14faa62..51b89120 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java @@ -19,7 +19,7 @@ * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.asitplus.eidas.specific.connector.builder; @@ -54,30 +54,37 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder public IAuthData buildAuthenticationData(IRequest pendingReq) throws EaafAuthenticationException { final IAuthProcessDataContainer authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - final AuthenticationData authData = new AuthenticationData(); + AuthenticationData authData = new AuthenticationData(); - try { - generateDeprecatedBasicAuthData(authData, pendingReq, authProcessData); + String eidMode = pendingReq.getServiceProviderConfiguration() + .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); - // set specific informations - authData.setSsoSessionValidTo(new Date(new Date().getTime() - + MsEidasNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); + if (eidMode.equals("new")) { - } catch (EaafBuilderException | EaafParserException | EaafConfigurationException - | XPathException | DOMException e) { - log.warn("Can not build authentication data from auth. process information"); - throw new EaafAuthenticationException("builder.11", new Object[] { e.getMessage() }, e); + authData = (AuthenticationData) super.buildAuthenticationData(pendingReq); - } + } else { + try { + generateDeprecatedBasicAuthData(authData, pendingReq, authProcessData); - return authData; + // set specific informations + authData.setSsoSessionValidTo(new Date(new Date().getTime() + + MsEidasNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); + + } catch (EaafBuilderException | EaafParserException | EaafConfigurationException + | XPathException | DOMException e) { + log.warn("Can not build authentication data from auth. process information"); + throw new EaafAuthenticationException("builder.11", new Object[]{e.getMessage()}, e); + } + } + return authData; } @Override protected IAuthData buildDeprecatedAuthData(IRequest arg0) throws EaafException { return new AuthenticationData(); - + } @Override @@ -103,7 +110,7 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder @Override protected Pair getEncryptedBpkFromPvpAttribute(IAuthProcessDataContainer arg0, - AuthenticationData arg1, ISpConfiguration arg2) throws EaafBuilderException { + AuthenticationData arg1, ISpConfiguration arg2) throws EaafBuilderException { return null; } diff --git a/connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder b/connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder new file mode 100644 index 00000000..8508cc4b --- /dev/null +++ b/connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder @@ -0,0 +1,2 @@ +at.asitplus.eidas.specific.connector.attributes.AuthBlockAttributeBuilder +at.asitplus.eidas.specific.connector.attributes.EidasBindAttributeBuilder diff --git a/connector/src/main/resources/SpringTest_connector.beans.xml b/connector/src/main/resources/SpringTest_connector.beans.xml new file mode 100644 index 00000000..5cf0d5b8 --- /dev/null +++ b/connector/src/main/resources/SpringTest_connector.beans.xml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java new file mode 100644 index 00000000..4ae2a34d --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java @@ -0,0 +1,95 @@ +package at.asitplus.eidas.specific.connector.test; + + +import at.asitplus.eidas.specific.connector.builder.AuthenticationDataBuilder; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.config.InitializationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({"/applicationContext.xml", + "/SpringTest_connector.beans.xml", + "/eaaf_core.beans.xml", + "/eaaf_pvp.beans.xml", + "/eaaf_pvp_idp.beans.xml", + "/spring/SpringTest-context_simple_storage.xml" }) +@WebAppConfiguration +public class AuthenticationDataBuilderTest { + + @Autowired + private AuthenticationDataBuilder authenticationDataBuilder; + + @Autowired(required = true) + private IConfiguration basicConfig; + + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private TestRequestImpl pendingReq; + + private DummySpConfiguration oaParam; + + + @BeforeClass + public static void classInitializer() throws InitializationException, ComponentInitializationException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_3.properties"); + + EaafOpenSaml3xInitializer.eaafInitialize(); + } + + @Before + public void initialize() throws EaafStorageException { + httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + final Map spConfig = new HashMap<>(); + spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); + spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); + spConfig.put("eidMode", "new"); + oaParam = new DummySpConfiguration(spConfig, basicConfig); + + pendingReq = new TestRequestImpl(); + pendingReq.setAuthUrl("https://localhost/ms_connector"); + pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); + pendingReq.setSpConfig(oaParam); + pendingReq.getSessionData(AuthProcessDataWrapper.class).setEidProcess(true); + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.SZR_AUTHBLOCK, RandomStringUtils.randomAlphanumeric(20)); + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.EIDAS_BIND, RandomStringUtils.randomAlphanumeric(20)); + + + LocaleContextHolder.resetLocaleContext(); + } + + @Test + public void first() throws EaafAuthenticationException { + authenticationDataBuilder.buildAuthenticationData(pendingReq); + } + +} diff --git a/connector/src/test/resources/config/junit_config_3.properties b/connector/src/test/resources/config/junit_config_3.properties new file mode 100644 index 00000000..2abda7db --- /dev/null +++ b/connector/src/test/resources/config/junit_config_3.properties @@ -0,0 +1,115 @@ +## Basic service configuration +eidas.ms.context.url.prefix= +eidas.ms.context.url.request.validation=false + +eidas.ms.context.use.clustermode=true + +##Monitoring +eidas.ms.monitoring.eIDASNode.metadata.url= + + +##Specific logger configuration +eidas.ms.technicallog.write.MDS.into.techlog=true +eidas.ms.revisionlog.write.MDS.into.revisionlog=true +eidas.ms.revisionlog.logIPAddressOfUser=true + +##Directory for static Web content +eidas.ms.webcontent.static.directory=webcontent/ +eidas.ms.webcontent.templates=templates/ +eidas.ms.webcontent.properties=properties/messages +eidas.ms.webcontent.templates.countryselection=countrySelection.html + +## extended validation of pending-request Id's +eidas.ms.core.pendingrequestid.maxlifetime=300 +eidas.ms.core.pendingrequestid.digist.algorithm=HmacSHA256 +eidas.ms.core.pendingrequestid.digist.secret=pendingReqIdSecret + +## eIDAS Ref. Implementation connector ### +eidas.ms.auth.eIDAS.node_v2.entityId=ownSpecificConnector +eidas.ms.auth.eIDAS.node_v2.forward.endpoint= +eidas.ms.auth.eIDAS.node_v2.forward.method=POST +eidas.ms.auth.eIDAS.node_v2.countrycode=AT +eidas.ms.auth.eIDAS.node_v2.publicSectorTargets=.* +eidas.ms.auth.eIDAS.node_v2.workarounds.addAlwaysProviderName=true +eidas.ms.auth.eIDAS.node_v2.workarounds.useRequestIdAsTransactionIdentifier=true +eidas.ms.auth.eIDAS.node_v2.workarounds.useStaticProviderNameForPublicSPs=true + +eidas.ms.auth.eIDAS.node_v2.loa.requested.minimum=http://eidas.europa.eu/LoA/substantial + +eidas.ms.auth.eIDAS.szrclient.useTestService=true +eidas.ms.auth.eIDAS.szrclient.endpoint.prod= +eidas.ms.auth.eIDAS.szrclient.endpoint.test=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.szrclient.ssl.keyStore.path=keys/junit.jks +eidas.ms.auth.eIDAS.szrclient.ssl.keyStore.password=password +eidas.ms.auth.eIDAS.szrclient.ssl.trustStore.path= +eidas.ms.auth.eIDAS.szrclient.ssl.trustStore.password= +eidas.ms.auth.eIDAS.szrclient.timeout.connection=15 +eidas.ms.auth.eIDAS.szrclient.timeout.response=30 +eidas.ms.auth.eIDAS.szrclient.params.vkz= + +eidas.ms.auth.eIDAS.szrclient.params.useSZRForbPKCalculation=false + + +#Raw eIDAS Id data storage +eidas.ms.auth.eIDAS.szrclient.workarounds.eidmapping.revisionlog.active=true + +eidas.ms.auth.eIDAS.szrclient.params.setPlaceOfBirthIfAvailable=true +eidas.ms.auth.eIDAS.szrclient.params.setBirthNameIfAvailable=true + +eidas.ms.auth.eIDAS.szrclient.debug.logfullmessages=true +eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution=true + +##without mandates +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.0=PersonIdentifier,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.1=FamilyName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.2=FirstName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.onlynatural.3=DateOfBirth,true + +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.4=PlaceOfBirth,false +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.5=BirthName,false +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.6=Gender,false +eidas.ms.auth.eIDAS.node_v2.attributes.requested.de.onlynatural.7=CurrentAddress,false + +##with mandates ---- NOT FULLY SUPPORTED AT THE MOMENT ----- +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.0=PersonIdentifier,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.1=FamilyName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.2=FirstName,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.3=DateOfBirth,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.4=LegalPerson,true +eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true + + +## PVP2 S-Profile end-point configuration +eidas.ms.pvp2.keystore.path=keys/junit.jks +eidas.ms.pvp2.keystore.password=password +eidas.ms.pvp2.key.metadata.alias= +eidas.ms.pvp2.key.metadata.password= +eidas.ms.pvp2.key.signing.alias= +eidas.ms.pvp2.key.signing.password= +eidas.ms.pvp2.metadata.validity=24 + +eidas.ms.pvp2.metadata.organisation.name=JUnit +eidas.ms.pvp2.metadata.organisation.friendyname=For testing with jUnit +eidas.ms.pvp2.metadata.organisation.url=http://junit.test +eidas.ms.pvp2.metadata.contact.givenname=Max +eidas.ms.pvp2.metadata.contact.surname=Mustermann +eidas.ms.pvp2.metadata.contact.email=max@junit.test + +## Service Provider configuration +eidas.ms.sp.0.uniqueID= +eidas.ms.sp.0.pvp2.metadata.truststore=keys/junit.jks +eidas.ms.sp.0.pvp2.metadata.truststore.password=password +eidas.ms.sp.0.eidMode=new + +#eidas.ms.sp.0.friendlyName= +#eidas.ms.sp.0.pvp2.metadata.url= +#eidas.ms.sp.0.policy.allowed.requested.targets=.* +#eidas.ms.sp.0.policy.hasBaseIdTransferRestriction=false + + +##only for advanced config +eidas.ms.configuration.sp.disableRegistrationRequirement= +eidas.ms.configuration.restrictions.baseID.spTransmission= +eidas.ms.configuration.auth.default.countrycode= +eidas.ms.configuration.pvp.scheme.validation= +eidas.ms.configuration.pvp.enable.entitycategories= \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java index eac62aae..83a2afa6 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/Constants.java @@ -157,8 +157,8 @@ public class Constants { public static final String SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE = "ELEKTR_DOKUMENT"; // AuthBlock - public static final String SZR_AUTHBLOCK = "AUTHBLOCK"; - public static final String EIDAS_BIND = "EIDAS_BIND"; + public static final String SZR_AUTHBLOCK = "authData_AUTHBLOCK"; + public static final String EIDAS_BIND = "authData_EIDAS_BIND"; // TODO remove!!! diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index b141402a..86f28561 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -249,10 +249,10 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { ObjectMapper mapper = new ObjectMapper(); String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); - String jwsSignature = JoseUtils.createSignature(ks, KSALIAS, KSPASSWORD.toCharArray(), jwsPayload, false, KSALIAS);//TODO joseutils kopiern + String jwsSignature = JoseUtils.createSignature(ks, KSALIAS, KSPASSWORD.toCharArray(), jwsPayload, false, KSALIAS); authProcessData.setGenericDataToSession(Constants.SZR_AUTHBLOCK, jwsSignature); - authProcessData.setGenericDataToSession(Constants.EIDAS_BIND, jwsSignature); + authProcessData.setGenericDataToSession(Constants.EIDAS_BIND, signedEidasBind); } else { final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(personInfo); @@ -294,7 +294,14 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - if (eidMode.equals("new")) {} + if (eidMode.equals("new")) { + authProcessData.setForeigner(true); + authProcessData.setGenericDataToSession( + PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, + EidasResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get( + Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); + authProcessData.setQaaLevel(eidasResponse.getLevelOfAssurance()); + } else { if (identityLink == null) { log.error("ERnB did not return an identity link."); -- cgit v1.2.3 From 578841c3723da27525d5fffb37d4ccc3dffa7bb4 Mon Sep 17 00:00:00 2001 From: lalber Date: Tue, 3 Nov 2020 10:47:11 +0100 Subject: sunfire bug --- .../attributes/AuthBlockAttributeBuilder.java | 14 ++-- .../attributes/EidasBindAttributeBuilder.java | 15 +++-- .../modules/auth/eidas/v2/test/SzrClientTest.java | 78 +++++++++++----------- 3 files changed, 56 insertions(+), 51 deletions(-) diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java index ab5db0a6..e3e482ef 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java @@ -34,12 +34,14 @@ import java.text.SimpleDateFormat; @PvpMetadata public class AuthBlockAttributeBuilder implements IPvpAttributeBuilder { - private static final String AUTHBLOCK_FRIENDLY_NAME = "AUTHBLOCK"; - private static final String AUTHBLOCK_NAME = "urn:oid:x.x.x.x"; //TODO set oid +// private static final String AUTHBLOCK_FRIENDLY_NAME = "AUTHBLOCK"; +// private static final String AUTHBLOCK_NAME = "urn:oid:x.x.x.x"; //TODO set oid +String EID_AUTHBLOCK_SIGNED_NAME = "urn:eidgvat:attributes.authblock.signed"; +String EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME = "userAuthBlock"; @Override public String getName() { - return AUTHBLOCK_NAME; + return EID_AUTHBLOCK_SIGNED_NAME; } @Override @@ -48,17 +50,17 @@ public class AuthBlockAttributeBuilder implements IPvpAttributeBuilder { String authBlock = authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class); if (authBlock != null) { - return g.buildStringAttribute(AUTHBLOCK_FRIENDLY_NAME, AUTHBLOCK_NAME, authBlock); + return g.buildStringAttribute(EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME, EID_AUTHBLOCK_SIGNED_NAME, authBlock); } else { - throw new UnavailableAttributeException(AUTHBLOCK_NAME); + throw new UnavailableAttributeException(EID_AUTHBLOCK_SIGNED_NAME); } } @Override public ATT buildEmpty(final IAttributeGenerator g) { - return g.buildEmptyAttribute(AUTHBLOCK_FRIENDLY_NAME, AUTHBLOCK_NAME); + return g.buildEmptyAttribute(EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME, EID_AUTHBLOCK_SIGNED_NAME); } } diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java index c6dfed1a..e43689a1 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java @@ -31,15 +31,18 @@ import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; import java.text.DateFormat; import java.text.SimpleDateFormat; +import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_EIDBIND_FRIENDLY_NAME; +import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_EIDBIND_NAME; + @PvpMetadata public class EidasBindAttributeBuilder implements IPvpAttributeBuilder { - private static final String EIDASBIND_FRIENDLY_NAME = "EIDASBIND"; - private static final String EIDASBIND_NAME = "urn:oid:x.x.x.x"; //TODO set oid +// private static final String EIDASBIND_FRIENDLY_NAME = "EIDASBIND"; +// private static final String EIDASBIND_NAME = "urn:oid:x.x.x.x"; //TODO set oid @Override public String getName() { - return EIDASBIND_NAME; + return EID_EIDBIND_NAME; } @Override @@ -48,17 +51,17 @@ public class EidasBindAttributeBuilder implements IPvpAttributeBuilder { String eidasBind = authData.getGenericData(Constants.EIDAS_BIND, String.class); if (eidasBind != null) { - return g.buildStringAttribute(EIDASBIND_FRIENDLY_NAME, EIDASBIND_NAME, eidasBind); + return g.buildStringAttribute(EID_EIDBIND_FRIENDLY_NAME, EID_EIDBIND_NAME, eidasBind); } else { - throw new UnavailableAttributeException(EIDASBIND_NAME); + throw new UnavailableAttributeException(EID_EIDBIND_NAME); } } @Override public ATT buildEmpty(final IAttributeGenerator g) { - return g.buildEmptyAttribute(EIDASBIND_FRIENDLY_NAME, EIDASBIND_NAME); + return g.buildEmptyAttribute(EID_EIDBIND_FRIENDLY_NAME, EID_EIDBIND_NAME); } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index d9275089..086a1817 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -109,45 +109,45 @@ public class SzrClientTest { - @Test -public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception { - SZR szrMock = soap.mock(SZR.class, "hhttp://localhost:1234/demoszr"); - - final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); - final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); - szrResponse.getOut().add(result1); - - when(szrMock.getBPKFromStammzahlEncrypted(anyList())) - .thenReturn(Arrays.asList(result1)); - -// szrMock.getStammzahlEncrypted() TODO ??? - } - - @Test - public void getBcBindValid() throws SZRException_Exception, SzrCommunicationException { - SZR szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); - - final SignContentResponse szrResponse = new SignContentResponse(); - final SignContentEntry result1 = new SignContentEntry(); - final SignContentResponseType content = new SignContentResponseType(); - content.getOut().add(result1); - szrResponse.setSignContentResponse(content); - - result1.setKey("bcBindReq"); - result1.setValue(RandomStringUtils.randomAlphanumeric(100)); - - when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); - - final String bcBind = szrClient.getBcBind( - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10)); - - Assert.assertNotNull("bcBind is null", bcBind); - Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); - - - } +// @Test +//public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception { +// SZR szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); +// +// final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); +// final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); +// szrResponse.getOut().add(result1); +// +// when(szrMock.getBPKFromStammzahlEncrypted(anyList())) +// .thenReturn(Arrays.asList(result1)); +// +//// szrMock.getStammzahlEncrypted() TODO ??? +// } +// +// @Test +// public void getBcBindValid() throws SZRException_Exception, SzrCommunicationException { +// SZR szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); +// +// final SignContentResponse szrResponse = new SignContentResponse(); +// final SignContentEntry result1 = new SignContentEntry(); +// final SignContentResponseType content = new SignContentResponseType(); +// content.getOut().add(result1); +// szrResponse.setSignContentResponse(content); +// +// result1.setKey("bcBindReq"); +// result1.setValue(RandomStringUtils.randomAlphanumeric(100)); +// +// when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); +// +// final String bcBind = szrClient.getBcBind( +// RandomStringUtils.randomAlphabetic(10), +// RandomStringUtils.randomAlphabetic(10), +// RandomStringUtils.randomAlphabetic(10)); +// +// Assert.assertNotNull("bcBind is null", bcBind); +// Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); +// +// +// } @Test -- cgit v1.2.3 From 5c1635840f3e0826d0003f915d29b01e62344e4f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 3 Nov 2020 11:43:11 +0100 Subject: fix broken jUnit tests that use SZR MockUp --- .../modules/auth/eidas/v2/test/SzrClientTest.java | 131 ++++++++++++--------- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 97 ++++++--------- 2 files changed, 111 insertions(+), 117 deletions(-) diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index 086a1817..c957e20c 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -44,6 +44,7 @@ import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.cxf.binding.soap.SoapFault; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; @@ -74,7 +75,17 @@ import at.gv.egiz.eaaf.core.exceptions.EaafParserException; import at.gv.egiz.eaaf.core.impl.data.Triple; import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; import at.gv.egiz.eaaf.core.impl.utils.DomUtils; -import szrservices.*; +import szrservices.GetBPKFromStammzahlEncryptedResponse; +import szrservices.GetBPKFromStammzahlEncryptedResponseType; +import szrservices.GetIdentityLinkEidasResponse; +import szrservices.IdentityLinkType; +import szrservices.PersonInfoType; +import szrservices.SZR; +import szrservices.SZRException_Exception; +import szrservices.SignContentEntry; +import szrservices.SignContentResponse; +import szrservices.SignContentResponseType; +import szrservices.TravelDocumentType; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_tasks_test.xml") @@ -92,6 +103,12 @@ public class SzrClientTest { private static final String eIDASeID = "IS/AT/1234sdgsdfg56789ABCDEF"; private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; + private SZR szrMock = null; + + + @Rule + public SoapServiceRule soap = SoapServiceRule.newInstance(); + /** * jUnit class initializer. * @@ -104,56 +121,59 @@ public class SzrClientTest { } - @Rule - public SoapServiceRule soap = SoapServiceRule.newInstance(); + /** + * Initialize jUnit test. + * + */ + @Before + public void initializer() { + if (szrMock == null) { + szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); + + } + } + + + @Test + public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception { + final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); + final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); + szrResponse.getOut().add(result1); + + when(szrMock.getBPKFromStammzahlEncrypted(anyList())) + .thenReturn(Arrays.asList(result1)); + +// szrMock.getStammzahlEncrypted() TODO ??? + } + @Test + public void getBcBindValid() throws SZRException_Exception, SzrCommunicationException { + final SignContentResponse szrResponse = new SignContentResponse(); + final SignContentEntry result1 = new SignContentEntry(); + final SignContentResponseType content = new SignContentResponseType(); + content.getOut().add(result1); + szrResponse.setSignContentResponse(content); + + result1.setKey("bcBindReq"); + result1.setValue(RandomStringUtils.randomAlphanumeric(100)); + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); -// @Test -//public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception { -// SZR szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); -// -// final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); -// final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); -// szrResponse.getOut().add(result1); -// -// when(szrMock.getBPKFromStammzahlEncrypted(anyList())) -// .thenReturn(Arrays.asList(result1)); -// -//// szrMock.getStammzahlEncrypted() TODO ??? -// } -// -// @Test -// public void getBcBindValid() throws SZRException_Exception, SzrCommunicationException { -// SZR szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); -// -// final SignContentResponse szrResponse = new SignContentResponse(); -// final SignContentEntry result1 = new SignContentEntry(); -// final SignContentResponseType content = new SignContentResponseType(); -// content.getOut().add(result1); -// szrResponse.setSignContentResponse(content); -// -// result1.setKey("bcBindReq"); -// result1.setValue(RandomStringUtils.randomAlphanumeric(100)); -// -// when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); -// -// final String bcBind = szrClient.getBcBind( -// RandomStringUtils.randomAlphabetic(10), -// RandomStringUtils.randomAlphabetic(10), -// RandomStringUtils.randomAlphabetic(10)); -// -// Assert.assertNotNull("bcBind is null", bcBind); -// Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); -// -// -// } + final String bcBind = szrClient.getBcBind( + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10)); + Assert.assertNotNull("bcBind is null", bcBind); + Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); + + } @Test public void getIdentityLinkRawModeValidResponse() throws SZRException_Exception, EaafParserException, - NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException, JAXBException { - setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml", "http://localhost:1234/demoszr"); + NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException, + JAXBException { + setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml"); try { log.debug("Starting connecting SZR Gateway"); @@ -188,8 +208,7 @@ public class SzrClientTest { public void getIdentityLinkRawModeErrorTravelerDocExists() throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException, JAXBException, ParserConfigurationException, SAXException { - setSzrExceptionIdentityLink("/data/szr/szr_resp_error_travelerdocexists.xml", - "http://localhost:1234/demoszr"); + setSzrExceptionIdentityLink("/data/szr/szr_resp_error_travelerdocexists.xml"); try { log.debug("Starting connecting SZR Gateway"); @@ -221,11 +240,11 @@ public class SzrClientTest { "no VKZ defined")); if (bPK.isEmpty()) { - throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); + throw new SzrCommunicationException("ernb.01", new Object[] { "bPK list is empty" }); } - for (String b : bPK) { + for (final String b : bPK) { if (StringUtils.isEmpty(b)) { - throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); + throw new SzrCommunicationException("ernb.01", new Object[] { "bPK is null or empty" }); } } @@ -237,27 +256,23 @@ public class SzrClientTest { } - private void setSzrResponseIdentityLink(String responseXmlPath, String serviceUrl) throws JAXBException, + private void setSzrResponseIdentityLink(String responseXmlPath) throws JAXBException, SZRException_Exception { - final SZR szrServiceMock = soap.mock(SZR.class, serviceUrl); final JAXBContext jaxbContext = JAXBContext.newInstance( szrservices.ObjectFactory.class, - org.xmlsoap.schemas.ws._2002._04.secext.ObjectFactory.class, org.w3._2001._04.xmldsig_more.ObjectFactory.class, org.w3._2000._09.xmldsig.ObjectFactory.class, - at.gv.egov.pvp1.ObjectFactory.class, at.gv.e_government.reference.namespace.persondata._20020228.ObjectFactory.class); final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); final GetIdentityLinkEidasResponse szrResponse = (GetIdentityLinkEidasResponse) jaxbUnmarshaller .unmarshal(this.getClass().getResourceAsStream(responseXmlPath)); - when(szrServiceMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenReturn(szrResponse + when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenReturn(szrResponse .getGetIdentityLinkReturn()); } - private void setSzrExceptionIdentityLink(String responseXmlPath, String serviceUrl) throws JAXBException, + private void setSzrExceptionIdentityLink(String responseXmlPath) throws JAXBException, ParserConfigurationException, SAXException, IOException, SZRException_Exception { - final SZR szrServiceMock = soap.mock(SZR.class, serviceUrl); final Element detailerror = DomUtils.parseXmlNonValidating(this.getClass().getResourceAsStream( responseXmlPath)); final javax.xml.namespace.QName qName = new javax.xml.namespace.QName("urn:SZRServices", "F455", "p344"); @@ -267,7 +282,7 @@ public class SzrClientTest { qName); fault.setRole("urn:SZRServices"); fault.setDetail(detailerror); - when(szrServiceMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenThrow(fault); + when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenThrow(fault); } @@ -279,7 +294,7 @@ public class SzrClientTest { return hashBase64; } catch (final Exception ex) { - throw new EidasSAuthenticationException("internal.03", new Object[]{}, ex); + throw new EidasSAuthenticationException("internal.03", new Object[] {}, ex); } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index 7a214744..031ea825 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -1,82 +1,59 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; +import static org.mockito.ArgumentMatchers.any; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.skjolberg.mockito.soap.SoapServiceRule; + import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeEidProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateAuthnRequestTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummySpecificCommunicationService; -import at.gv.e_government.reference.namespace.persondata._20020228.PostalAddressType; import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; import at.gv.egiz.eaaf.core.api.data.EaafConstants; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.controller.tasks.FinalizeAuthenticationTask; import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSortedSet; -import com.google.common.collect.Maps; -import com.skjolberg.mockito.soap.SoapServiceRule; -import eu.eidas.auth.commons.EIDASStatusCode; import eu.eidas.auth.commons.attribute.AttributeDefinition; -import eu.eidas.auth.commons.attribute.AttributeValueMarshaller; import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; import eu.eidas.auth.commons.attribute.PersonType; -import eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller; -import eu.eidas.auth.commons.attribute.impl.StringAttributeValueMarshaller; -import eu.eidas.auth.commons.light.ILightRequest; -import eu.eidas.auth.commons.light.ILightResponse; -import eu.eidas.auth.commons.light.impl.LightRequest; -import eu.eidas.auth.commons.light.impl.LightResponse; -import eu.eidas.auth.commons.light.impl.ResponseStatus; import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; -import eu.eidas.specificcommunication.exception.SpecificCommunicationException; import lombok.val; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.joda.time.DateTime; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.internal.builders.JUnit3Builder; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import org.mockito.Spy; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import szrservices.*; - -import javax.xml.namespace.QName; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; - -import static org.mockito.ArgumentMatchers.any; -import static org.powermock.api.mockito.PowerMockito.*; +import szrservices.PersonInfoType; +import szrservices.SZR; +import szrservices.SignContentEntry; +import szrservices.SignContentResponseType; @RunWith(SpringJUnit4ClassRunner.class) //@RunWith(PowerMockRunner.class) @@ -104,7 +81,9 @@ public class CreateIdentityLinkTaskEidNewTest { private TestRequestImpl pendingReq; private DummySpConfiguration oaParam; private SZR szrMock; - final SoapServiceRule soap = SoapServiceRule.newInstance(); + + @Rule + public final SoapServiceRule soap = SoapServiceRule.newInstance(); /** * jUnit class initializer. -- cgit v1.2.3 From 9704a357d117c48ed66d0b2d71b95747e1b73fef Mon Sep 17 00:00:00 2001 From: lalber Date: Tue, 3 Nov 2020 12:10:28 +0100 Subject: code style fixes --- .../modules/auth/eidas/v2/szr/SzrClient.java | 38 +++++++++++++++------- .../eidas/v2/tasks/CreateIdentityLinkTask.java | 19 ++++++----- 2 files changed, 37 insertions(+), 20 deletions(-) diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java index 5a551649..d2ce2f5d 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java @@ -33,7 +33,11 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import javax.annotation.PostConstruct; import javax.net.ssl.KeyManager; @@ -57,7 +61,6 @@ import javax.xml.ws.handler.Handler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.StopWatch; import org.apache.cxf.configuration.jsse.TLSClientParameters; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; @@ -80,7 +83,20 @@ import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.impl.utils.DomUtils; import at.gv.egiz.eaaf.core.impl.utils.FileUtils; import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; -import szrservices.*; +import szrservices.GetBPK; +import szrservices.GetBPKResponse; +import szrservices.GetIdentityLinkEidas; +import szrservices.GetIdentityLinkEidasResponse; +import szrservices.IdentityLinkType; +import szrservices.JwsHeaderParam; +import szrservices.ObjectFactory; +import szrservices.PersonInfoType; +import szrservices.SZR; +import szrservices.SZRException_Exception; +import szrservices.SignContent; +import szrservices.SignContentEntry; +import szrservices.SignContentResponseType; + @Service("SZRClientForeIDAS") public class SzrClient { @@ -89,6 +105,13 @@ public class SzrClient { private static final String CLIENT_DEFAULT = "DefaultClient"; private static final String CLIENT_RAW = "RawClient"; + private static final String ATTR_NAME_VSZ = "urn:eidgvat:attributes.vsz.value"; + private static final String ATTR_NAME_PUBKEYS = "urn:eidgvat:attributes.user.pubkeys"; + private static final String ATTR_NAME_STATUS = "urn:eidgvat:attributes.eid.status"; + private static final String KEY_BC_BIND = "bcBindReq"; + private static final String JOSE_HEADER_USERCERTPINNING_TYPE = "urn:at.gv.eid:bindtype"; + private static final String JOSE_HEADER_USERCERTPINNING_EIDASBIND = "urn:at.gv.eid:eidasBind"; + @Autowired private IConfiguration basicConfig; @@ -232,13 +255,6 @@ public class SzrClient { public String getBcBind(final String vsz, final String bindingPubKey, final String eidStatus) throws SzrCommunicationException { - final String ATTR_NAME_VSZ = "urn:eidgvat:attributes.vsz.value"; - final String ATTR_NAME_PUBKEYS = "urn:eidgvat:attributes.user.pubkeys"; - final String ATTR_NAME_STATUS = "urn:eidgvat:attributes.eid.status"; - final String KEY_BC_BIND = "bcBindReq"; - final String JOSE_HEADER_USERCERTPINNING_TYPE = "urn:at.gv.eid:bindtype"; - final String JOSE_HEADER_USERCERTPINNING_EIDASBIND = "urn:at.gv.eid:eidasBind"; - final Map bcBindMap = new HashMap<>(); bcBindMap.put(ATTR_NAME_VSZ, vsz); bcBindMap.put(ATTR_NAME_STATUS, eidStatus); @@ -264,7 +280,7 @@ public class SzrClient { if (resp == null || resp.getOut().isEmpty() || resp.getOut().get(0).getValue() == null) { - throw new SzrCommunicationException("ernb.01", new Object[]{"BcBind response empty"}); //TODO check error handling + throw new SzrCommunicationException("ernb.01", new Object[]{"BcBind response empty"}); } return resp.getOut().get(0).getValue(); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index 86f28561..765f7928 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -62,7 +62,6 @@ import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.jce.PKCS10CertificationRequest; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -74,7 +73,7 @@ import szrservices.TravelDocumentType; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.*; +import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Provider; @@ -103,8 +102,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { EaafKeyStoreFactory keyStoreFactory; Pair ks; - private final String KSPASSWORD = "f/+saJBc3a}*/T^s"; - private final String KSALIAS = "connectorkeypair"; + private static final String KSPASSWORD = "f/+saJBc3a}*/T^s"; + private static final String KSALIAS = "connectorkeypair"; /* * (non-Javadoc) @@ -238,18 +237,20 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { String vsz = szrClient.getEncryptedStammzahl(personInfo); // build Keystore - String pK64 = getPkFromKeystore(); + String pk64 = getPkFromKeystore(); // setzte Keystore in config ?path? lade rein // key pair art siehe jose utils - String signedEidasBind = szrClient.getBcBind(vsz, pK64, "urn:eidgvat:eid.status.eidas"); //eidstatus TODO as config? + String signedEidasBind = szrClient.getBcBind(vsz, pk64, "urn:eidgvat:eid.status.eidas"); + //TODO eidStatus as config? //build AuthBlock JWS ObjectMapper mapper = new ObjectMapper(); String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); - String jwsSignature = JoseUtils.createSignature(ks, KSALIAS, KSPASSWORD.toCharArray(), jwsPayload, false, KSALIAS); + String jwsSignature = JoseUtils.createSignature(ks, KSALIAS, KSPASSWORD.toCharArray(), jwsPayload, + false, KSALIAS); authProcessData.setGenericDataToSession(Constants.SZR_AUTHBLOCK, jwsSignature); authProcessData.setGenericDataToSession(Constants.EIDAS_BIND, signedEidasBind); @@ -301,8 +302,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { EidasResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get( Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); authProcessData.setQaaLevel(eidasResponse.getLevelOfAssurance()); - } - else { + + } else { if (identityLink == null) { log.error("ERnB did not return an identity link."); throw new SzrCommunicationException("ernb.00", null); -- cgit v1.2.3 From e9a093a8d10dcce01661ef5182633e9a296e737e Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 4 Nov 2020 14:27:10 +0100 Subject: fix for EvaluateCountrySelectionTaskTest and GenerateCountrySelectionFrameTaskTest --- .../connector/attributes/AuthBlockAttributeBuilder.java | 14 ++++++-------- .../connector/attributes/EidasBindAttributeBuilder.java | 10 ++++------ .../connector/builder/AuthenticationDataBuilder.java | 7 ++++--- .../test/task/EvaluateCountrySelectionTaskTest.java | 2 +- .../test/task/GenerateCountrySelectionFrameTaskTest.java | 2 +- 5 files changed, 16 insertions(+), 19 deletions(-) diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java index e3e482ef..c9cbdb84 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java @@ -15,7 +15,7 @@ * This product combines work with different licenses. See the "NOTICE" text file for details on the * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative * works that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.asitplus.eidas.specific.connector.attributes; @@ -28,16 +28,14 @@ import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; -import java.text.DateFormat; -import java.text.SimpleDateFormat; @PvpMetadata public class AuthBlockAttributeBuilder implements IPvpAttributeBuilder { -// private static final String AUTHBLOCK_FRIENDLY_NAME = "AUTHBLOCK"; -// private static final String AUTHBLOCK_NAME = "urn:oid:x.x.x.x"; //TODO set oid -String EID_AUTHBLOCK_SIGNED_NAME = "urn:eidgvat:attributes.authblock.signed"; -String EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME = "userAuthBlock"; + // private static final String AUTHBLOCK_FRIENDLY_NAME = "AUTHBLOCK"; + // private static final String AUTHBLOCK_NAME = "urn:oid:x.x.x.x"; //TODO set oid + private static final String EID_AUTHBLOCK_SIGNED_NAME = "urn:eidgvat:attributes.authblock.signed"; + private static final String EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME = "userAuthBlock"; @Override public String getName() { @@ -46,7 +44,7 @@ String EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME = "userAuthBlock"; @Override public ATT build(final ISpConfiguration oaParam, final IAuthData authData, - final IAttributeGenerator g) throws AttributeBuilderException { + final IAttributeGenerator g) throws AttributeBuilderException { String authBlock = authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class); if (authBlock != null) { diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java index e43689a1..53f52ab3 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java @@ -15,7 +15,7 @@ * This product combines work with different licenses. See the "NOTICE" text file for details on the * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative * works that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.asitplus.eidas.specific.connector.attributes; @@ -28,8 +28,6 @@ import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_EIDBIND_FRIENDLY_NAME; import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_EIDBIND_NAME; @@ -37,8 +35,8 @@ import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_ @PvpMetadata public class EidasBindAttributeBuilder implements IPvpAttributeBuilder { -// private static final String EIDASBIND_FRIENDLY_NAME = "EIDASBIND"; -// private static final String EIDASBIND_NAME = "urn:oid:x.x.x.x"; //TODO set oid + // private static final String EIDASBIND_FRIENDLY_NAME = "EIDASBIND"; + // private static final String EIDASBIND_NAME = "urn:oid:x.x.x.x"; //TODO set oid @Override public String getName() { @@ -47,7 +45,7 @@ public class EidasBindAttributeBuilder implements IPvpAttributeBuilder { @Override public ATT build(final ISpConfiguration oaParam, final IAuthData authData, - final IAttributeGenerator g) throws AttributeBuilderException { + final IAttributeGenerator g) throws AttributeBuilderException { String eidasBind = authData.getGenericData(Constants.EIDAS_BIND, String.class); if (eidasBind != null) { diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java index 51b89120..42163097 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java @@ -57,7 +57,7 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder AuthenticationData authData = new AuthenticationData(); String eidMode = pendingReq.getServiceProviderConfiguration() - .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); + .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); if (eidMode.equals("new")) { @@ -69,7 +69,7 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder // set specific informations authData.setSsoSessionValidTo(new Date(new Date().getTime() - + MsEidasNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); + + MsEidasNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); } catch (EaafBuilderException | EaafParserException | EaafConfigurationException | XPathException | DOMException e) { @@ -110,7 +110,8 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder @Override protected Pair getEncryptedBpkFromPvpAttribute(IAuthProcessDataContainer arg0, - AuthenticationData arg1, ISpConfiguration arg2) throws EaafBuilderException { + AuthenticationData arg1, + ISpConfiguration arg2) throws EaafBuilderException { return null; } diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java index 44b54366..9d590055 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java @@ -51,7 +51,7 @@ public class EvaluateCountrySelectionTaskTest { @BeforeClass public static void classInitializer() { final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current + "../basicConfig/default_config.properties"); + System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_1.properties"); } diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java index 61d68774..2a1d7cd4 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java @@ -49,7 +49,7 @@ public class GenerateCountrySelectionFrameTaskTest { @BeforeClass public static void classInitializer() { final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current + "../basicConfig/default_config.properties"); + System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_1.properties"); } -- cgit v1.2.3 From a9009a6f89c41dc19b85331dda676993c8a273b9 Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 4 Nov 2020 16:42:46 +0100 Subject: fix pw aliasname --- .../specific/connector/MsEidasNodeConstants.java | 4 + .../eidas/v2/tasks/CreateIdentityLinkTask.java | 187 ++++++++++----------- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 34 ++-- .../resources/config/junit_config_3.properties | 2 + 4 files changed, 107 insertions(+), 120 deletions(-) diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java index f33ccf44..d9aac126 100644 --- a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java @@ -96,6 +96,10 @@ public class MsEidasNodeConstants { "pvp2.metadata.truststore.password"; public static final String PROP_CONFIG_SP_EID_MODE = "eidMode"; + public static final String PROP_CONFIG_SP_AUTHBLOCK_PW = + "authblock.truststore.password"; + public static final String PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME = + "authblock.truststore.friendlyName"; public static final String PROP_CONFIG_SP_POLICY_ALLOWED_TARGETS = "policy.allowed.requested.targets"; public static final String PROP_CONFIG_SP_POLICY_BASEIDTRANSFER_RESTRICTION = "policy.hasBaseIdTransferRestriction"; diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index 765f7928..af260528 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -102,8 +102,6 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { EaafKeyStoreFactory keyStoreFactory; Pair ks; - private static final String KSPASSWORD = "f/+saJBc3a}*/T^s"; - private static final String KSALIAS = "connectorkeypair"; /* * (non-Javadoc) @@ -114,19 +112,18 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { * javax.servlet.http.HttpServletResponse) */ @Override - public void execute(ExecutionContext executionContext, - HttpServletRequest request, HttpServletResponse response) + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { try { final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - final ILightResponse eidasResponse = authProcessData.getGenericDataFromSession( - Constants.DATA_FULL_EIDAS_RESPONSE, ILightResponse.class); + final ILightResponse eidasResponse = authProcessData + .getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE, ILightResponse.class); String eidMode = pendingReq.getServiceProviderConfiguration() - .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); + .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); - final Map simpleAttrMap = convertEidasAttrToSimpleMap(eidasResponse.getAttributes() - .getAttributeMap()); + final Map simpleAttrMap = convertEidasAttrToSimpleMap( + eidasResponse.getAttributes().getAttributeMap()); IIdentityLink identityLink = null; String bpk = null; @@ -138,13 +135,12 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { writeMdsLogInformation(eidData); // connect SZR-Gateway - if (basicConfig.getBasicConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USEDUMMY, false)) { + if (basicConfig.getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USEDUMMY, false)) { log.warn("SZR-Dummy IS ACTIVE! IdentityLink is NOT VALID!!!!"); // create fake IdL // - fetch IdL template from resources - final InputStream s = CreateIdentityLinkTask.class.getResourceAsStream( - "/resources/xmldata/fakeIdL_IdL_template.xml"); + final InputStream s = CreateIdentityLinkTask.class + .getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); final Element idlTemplate = DomUtils.parseXmlValidating(s); identityLink = new SimpleIdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); @@ -153,33 +149,34 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { final Element idlassertion = identityLink.getSamlAssertion(); // - set fake baseID; - final Node prIdentification = XPathUtils.selectSingleNode(idlassertion, - SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + final Node prIdentification = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); prIdentification.getFirstChild().setNodeValue(eidData.getPseudonym()); // - set last name - final Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, - SimpleIdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); + final Node prFamilyName = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); prFamilyName.getFirstChild().setNodeValue(eidData.getFamilyName()); // - set first name - final Node prGivenName = XPathUtils.selectSingleNode(idlassertion, - SimpleIdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); + final Node prGivenName = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); prGivenName.getFirstChild().setNodeValue(eidData.getGivenName()); // - set date of birth - final Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, - SimpleIdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); + final Node prDateOfBirth = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); prDateOfBirth.getFirstChild().setNodeValue(eidData.getFormatedDateOfBirth()); identityLink = new SimpleIdentityLinkAssertionParser(idlassertion).parseIdentityLink(); new BpkBuilder(); - final Pair bpkCalc = BpkBuilder.generateAreaSpecificPersonIdentifier( - identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + final Pair bpkCalc = BpkBuilder + .generateAreaSpecificPersonIdentifier(identityLink.getIdentificationValue(), + identityLink.getIdentificationType(), + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); bpk = bpkCalc.getFirst(); } else { @@ -202,16 +199,16 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { eDocument.setDocumentNumber(eidData.getPseudonym()); // eID document information - eDocument.setDocumentType(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, - Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); + eDocument.setDocumentType(basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, + Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); // set PlaceOfBirth if available if (eidData.getPlaceOfBirth() != null) { log.trace("Find 'PlaceOfBirth' attribute: " + eidData.getPlaceOfBirth()); - if (basicConfig.getBasicConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETPLACEOFBIRTHIFAVAILABLE, - true)) { + if (basicConfig + .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETPLACEOFBIRTHIFAVAILABLE, + true)) { naturalPerson.setPlaceOfBirth(eidData.getPlaceOfBirth()); log.trace("Adding 'PlaceOfBirth' to ERnB request ... "); @@ -221,9 +218,9 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { // set BirthName if available if (eidData.getBirthName() != null) { log.trace("Find 'BirthName' attribute: " + eidData.getBirthName()); - if (basicConfig.getBasicConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETBIRTHNAMEIFAVAILABLE, - true)) { + if (basicConfig + .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETBIRTHNAMEIFAVAILABLE, + true)) { final AlternativeNameType alternativeName = new AlternativeNameType(); naturalPerson.setAlternativeName(alternativeName); alternativeName.setFamilyName(eidData.getBirthName()); @@ -234,12 +231,16 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { if (eidMode.equals("new")) { + String keyAlias = pendingReq.getServiceProviderConfiguration().getConfigurationValue( + MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME, ""); + + String keyPw = pendingReq.getServiceProviderConfiguration() + .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_PW, ""); + String vsz = szrClient.getEncryptedStammzahl(personInfo); // build Keystore - String pk64 = getPkFromKeystore(); - // setzte Keystore in config ?path? lade rein - // key pair art siehe jose utils + String pk64 = getPkFromKeystore(keyAlias, keyPw); String signedEidasBind = szrClient.getBcBind(vsz, pk64, "urn:eidgvat:eid.status.eidas"); @@ -249,8 +250,9 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { ObjectMapper mapper = new ObjectMapper(); String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); - String jwsSignature = JoseUtils.createSignature(ks, KSALIAS, KSPASSWORD.toCharArray(), jwsPayload, - false, KSALIAS); + + String jwsSignature = JoseUtils + .createSignature(ks, keyAlias, keyPw.toCharArray(), jwsPayload, false, keyAlias); authProcessData.setGenericDataToSession(Constants.SZR_AUTHBLOCK, jwsSignature); authProcessData.setGenericDataToSession(Constants.EIDAS_BIND, signedEidasBind); @@ -264,31 +266,29 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { // write ERnB inputdata into revisionlog if (basicConfig.getBasicConfigurationBoolean( Constants.CONIG_PROPS_EIDAS_SZRCLIENT_WORKAROUND_REVISIONLOGDATASTORE_ACTIVE, false)) { - revisionsLogger.logEvent(pendingReq, - MsConnectorEventCodes.SZR_ERNB_EIDAS_RAW_ID, - (String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)); - revisionsLogger.logEvent(pendingReq, - MsConnectorEventCodes.SZR_ERNB_EIDAS_ERNB_ID, eidData.getPseudonym()); + revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_ERNB_EIDAS_RAW_ID, + (String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)); + revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_ERNB_EIDAS_ERNB_ID, eidData.getPseudonym()); } // get bPK from SZR - if (basicConfig.getBasicConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { - bpk = szrClient.getBpk( - personInfo, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, - "no VKZ defined")).get(0); + if (basicConfig + .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { + bpk = szrClient + .getBpk(personInfo, pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), + basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")) + .get(0); } else { log.debug("Calculating bPK from baseId ... "); new BpkBuilder(); - final Pair bpkCalc = BpkBuilder.generateAreaSpecificPersonIdentifier( - identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + final Pair bpkCalc = BpkBuilder + .generateAreaSpecificPersonIdentifier(identityLink.getIdentificationValue(), + identityLink.getIdentificationType(), + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); bpk = bpkCalc.getFirst(); } @@ -297,10 +297,9 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { if (eidMode.equals("new")) { authProcessData.setForeigner(true); - authProcessData.setGenericDataToSession( - PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, - EidasResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get( - Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, EidasResponseUtils + .parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)) + .getFirst()); authProcessData.setQaaLevel(eidasResponse.getLevelOfAssurance()); } else { @@ -310,11 +309,12 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_IDL_RECEIVED, - identityLink.getSamlAssertion().getAttribute(SimpleIdentityLinkAssertionParser.ASSERTIONID)); + identityLink.getSamlAssertion() + .getAttribute(SimpleIdentityLinkAssertionParser.ASSERTIONID)); if (bpk == null) { log.error("ERnB did not return a bPK for target: " + pendingReq.getServiceProviderConfiguration() - .getAreaSpecificTargetIdentifier()); + .getAreaSpecificTargetIdentifier()); throw new SzrCommunicationException("ernb.01", null); } @@ -324,20 +324,16 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { authProcessData.setForeigner(true); authProcessData.setIdentityLink(identityLink); - authProcessData.setGenericDataToSession( - PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, - EidasResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get( - Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, EidasResponseUtils + .parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)) + .getFirst()); // set bPK and bPKType into auth session - authProcessData.setGenericDataToSession( - PvpAttributeDefinitions.BPK_NAME, - extendBpkByPrefix( - bpk, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier())); - authProcessData.setGenericDataToSession( - PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.BPK_NAME, extendBpkByPrefix(bpk, pendingReq + .getServiceProviderConfiguration().getAreaSpecificTargetIdentifier())); + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); // store pending-request requestStoreage.storePendingRequest(pendingReq); @@ -355,17 +351,17 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - private String getPkFromKeystore() throws EaafException, KeyStoreException { + private String getPkFromKeystore(String keyAlias, String keyPw) throws EaafException, KeyStoreException { KeyStoreConfiguration configuration = new KeyStoreConfiguration(); final String current = new java.io.File(".").toURI().toString(); configuration.setSoftKeyStoreFilePath(current + "src/test/resources/keystore/teststore.jks"); - configuration.setSoftKeyStorePassword(KSPASSWORD); //TODO from config + configuration.setSoftKeyStorePassword(keyPw); //TODO from config configuration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.JKS); - configuration.setFriendlyName(KSALIAS); - configuration.setKeyStoreName(KSALIAS); + configuration.setFriendlyName(keyAlias); + configuration.setKeyStoreName(keyAlias); ks = keyStoreFactory.buildNewKeyStore(configuration); - val publicKey = ks.getFirst().getCertificate(KSALIAS).getPublicKey(); + val publicKey = ks.getFirst().getCertificate(keyAlias).getPublicKey(); return Base64.getEncoder().encodeToString(publicKey.getEncoded()); } @@ -400,8 +396,7 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { final Class parameterizedType = el.getParameterizedType(); if (DateTime.class.equals(parameterizedType)) { - final DateTime attribute = EidasResponseUtils.translateDateAttribute(el, attributeMap.get(el) - .asList()); + final DateTime attribute = EidasResponseUtils.translateDateAttribute(el, attributeMap.get(el).asList()); if (attribute != null) { result.put(el.getFriendlyName(), attribute); log.trace("Find attr '" + el.getFriendlyName() + "' with value: " + attribute.toString()); @@ -411,8 +406,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } else if (PostalAddress.class.equals(parameterizedType)) { - final PostalAddress addressAttribute = EidasResponseUtils.translateAddressAttribute(el, attributeMap - .get(el).asList()); + final PostalAddress addressAttribute = EidasResponseUtils + .translateAddressAttribute(el, attributeMap.get(el).asList()); if (addressAttribute != null) { result.put(el.getFriendlyName(), addressAttribute); log.trace("Find attr '" + el.getFriendlyName() + "' with value: " + addressAttribute.toString()); @@ -422,8 +417,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } else { - final List natPersonIdObj = EidasResponseUtils.translateStringListAttribute(el, attributeMap - .get(el).asList()); + final List natPersonIdObj = EidasResponseUtils + .translateStringListAttribute(el, attributeMap.get(el).asList()); final String stringAttr = natPersonIdObj.get(0); if (StringUtils.isNotEmpty(stringAttr)) { result.put(el.getFriendlyName(), stringAttr); @@ -443,23 +438,19 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { private void writeMdsLogInformation(ErnbEidData eidData) { // log MDS and country code into technical log - if (basicConfig.getBasicConfigurationBoolean( - MsEidasNodeConstants.PROP_CONFIG_TECHNICALLOG_WRITE_MDS_INTO_TECH_LOG, false)) { - log.info("eIDAS Auth. for user: " - + eidData.getGivenName() + " " - + eidData.getFamilyName() + " " - + eidData.getFormatedDateOfBirth() + " " - + "from " + eidData.getCitizenCountryCode()); + if (basicConfig + .getBasicConfigurationBoolean(MsEidasNodeConstants.PROP_CONFIG_TECHNICALLOG_WRITE_MDS_INTO_TECH_LOG, false)) { + log.info("eIDAS Auth. for user: " + eidData.getGivenName() + " " + eidData.getFamilyName() + " " + eidData + .getFormatedDateOfBirth() + " " + "from " + eidData.getCitizenCountryCode()); } // log MDS and country code into revision log - if (basicConfig.getBasicConfigurationBoolean( - MsEidasNodeConstants.PROP_CONFIG_REVISIONLOG_WRITE_MDS_INTO_REVISION_LOG, false)) { + if (basicConfig + .getBasicConfigurationBoolean(MsEidasNodeConstants.PROP_CONFIG_REVISIONLOG_WRITE_MDS_INTO_REVISION_LOG, + false)) { revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.RESPONSE_FROM_EIDAS_MDSDATA, - "{" + eidData.getGivenName() + "," - + eidData.getFamilyName() + "," - + eidData.getFormatedDateOfBirth() + "," - + eidData.getCitizenCountryCode() + "}"); + "{" + eidData.getGivenName() + "," + eidData.getFamilyName() + "," + eidData + .getFormatedDateOfBirth() + "," + eidData.getCitizenCountryCode() + "}"); } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index 031ea825..00e01a2c 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -1,5 +1,8 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME; +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_PW; +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE; import static org.mockito.ArgumentMatchers.any; import static org.powermock.api.mockito.PowerMockito.when; @@ -81,6 +84,9 @@ public class CreateIdentityLinkTaskEidNewTest { private TestRequestImpl pendingReq; private DummySpConfiguration oaParam; private SZR szrMock; + + private static final String PW = "f/+saJBc3a}*/T^s"; + private static final String ALIAS = "connectorkeypair"; @Rule public final SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -112,13 +118,17 @@ public class CreateIdentityLinkTaskEidNewTest { final Map spConfig = new HashMap<>(); spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); - spConfig.put("eidMode", "new"); + spConfig.put(PROP_CONFIG_SP_EID_MODE, "new"); + spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_PW, PW); + spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME, ALIAS); oaParam = new DummySpConfiguration(spConfig, basicConfig); pendingReq = new TestRequestImpl(); AuthenticationResponse response = buildDummyAuthResponse(); + + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); pendingReq.setSpConfig(oaParam); pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); @@ -169,40 +179,20 @@ public class CreateIdentityLinkTaskEidNewTest { String test = szrMock.getStammzahlEncrypted(new PersonInfoType(), false); -// SZR szrMock2 = Mockito.mock(SZR.class, Mockito.CALLS_REAL_METHODS); when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); val signContentResp = new SignContentResponseType(); SignContentEntry signContentEntry = new SignContentEntry(); signContentEntry.setValue(RandomStringUtils.randomAlphanumeric(10)); signContentResp.getOut().add(signContentEntry); when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); -// when(szrMock2, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); - // Wie kann ich das vom Bean rein gehängte SZR mit dem Mock überschreiben? - task.execute(pendingReq, executionContext); -// authTask.execute(pendingReq, executionContext); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } -// val spyTask = spy(task); -// Map requiredAttributes = new HashMap<>(); -// requiredAttributes.put(Constants.eIDAS_ATTR_PERSONALIDENTIFIER, "asdf"); -// requiredAttributes.put(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, "asdf"); -// requiredAttributes.put(Constants.eIDAS_ATTR_CURRENTGIVENNAME, "asdf"); -// requiredAttributes.put(Constants.eIDAS_ATTR_DATEOFBIRTH, new DateTime()); -// requiredAttributes.put(Constants.eIDAS_ATTR_PLACEOFBIRTH, "adf"); -// requiredAttributes.put(Constants.eIDAS_ATTR_BIRTHNAME, "adf"); -// requiredAttributes.put(Constants.eIDAS_ATTR_CURRENTADDRESS, new PostalAddressType()); -// try { -// doReturn(requiredAttributes).when(spyTask, "convertEidasAttrToSimpleMap", (any(ImmutableMap.class))); -// spyTask.execute(pendingReq, executionContext); -// } catch (final Exception e) { -// e.printStackTrace(); -// Assert.fail(); -// } + } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties index 326e14fe..33207118 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties @@ -94,6 +94,8 @@ eidas.ms.sp.0.uniqueID= eidas.ms.sp.0.pvp2.metadata.truststore= eidas.ms.sp.0.pvp2.metadata.truststore.password= eidas.ms.sp.0.eidMode=new +eidas.ms.sp.0.authblock.truststore.password=f/+saJBc3a}*/T^s +eidas.ms.sp.0.authblock.truststore.friendlyName=connectorkeypair #eidas.ms.sp.0.friendlyName= #eidas.ms.sp.0.pvp2.metadata.url= -- cgit v1.2.3 From 3e422c60952d5892a0e568de8c28ce878610eb2f Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 4 Nov 2020 18:47:51 +0100 Subject: Attribute builder tests EidasBindAttributeBuilderTest and AuthBlockAttributeBuilderTest --- .../attributes/AuthBlockAttributeBuilder.java | 9 +- .../attributes/EidasBindAttributeBuilder.java | 6 +- .../attributes/AuthBlockAttributeBuilderTest.java | 97 ++++++++++++++++++++++ .../attributes/EidasBindAttributeBuilderTest.java | 92 ++++++++++++++++++++ .../eidas/v2/tasks/CreateIdentityLinkTask.java | 17 ++-- .../modules/auth/eidas/v2/test/SzrClientTest.java | 3 +- 6 files changed, 204 insertions(+), 20 deletions(-) create mode 100644 connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java create mode 100644 connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java index c9cbdb84..80f91e57 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java @@ -27,15 +27,14 @@ import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; +import org.apache.commons.lang3.StringUtils; @PvpMetadata public class AuthBlockAttributeBuilder implements IPvpAttributeBuilder { - // private static final String AUTHBLOCK_FRIENDLY_NAME = "AUTHBLOCK"; - // private static final String AUTHBLOCK_NAME = "urn:oid:x.x.x.x"; //TODO set oid - private static final String EID_AUTHBLOCK_SIGNED_NAME = "urn:eidgvat:attributes.authblock.signed"; - private static final String EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME = "userAuthBlock"; + public static final String EID_AUTHBLOCK_SIGNED_NAME = "urn:eidgvat:attributes.authblock.signed"; + public static final String EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME = "userAuthBlock"; @Override public String getName() { @@ -47,7 +46,7 @@ public class AuthBlockAttributeBuilder implements IPvpAttributeBuilder { final IAttributeGenerator g) throws AttributeBuilderException { String authBlock = authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class); - if (authBlock != null) { + if (StringUtils.isNotEmpty(authBlock)) { return g.buildStringAttribute(EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME, EID_AUTHBLOCK_SIGNED_NAME, authBlock); } else { diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java index 53f52ab3..a4fe8c6c 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/EidasBindAttributeBuilder.java @@ -27,7 +27,7 @@ import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; - +import org.apache.commons.lang3.StringUtils; import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_EIDBIND_FRIENDLY_NAME; import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_EIDBIND_NAME; @@ -35,8 +35,6 @@ import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_ @PvpMetadata public class EidasBindAttributeBuilder implements IPvpAttributeBuilder { - // private static final String EIDASBIND_FRIENDLY_NAME = "EIDASBIND"; - // private static final String EIDASBIND_NAME = "urn:oid:x.x.x.x"; //TODO set oid @Override public String getName() { @@ -48,7 +46,7 @@ public class EidasBindAttributeBuilder implements IPvpAttributeBuilder { final IAttributeGenerator g) throws AttributeBuilderException { String eidasBind = authData.getGenericData(Constants.EIDAS_BIND, String.class); - if (eidasBind != null) { + if (StringUtils.isNotEmpty(eidasBind)) { return g.buildStringAttribute(EID_EIDBIND_FRIENDLY_NAME, EID_EIDBIND_NAME, eidasBind); } else { diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java new file mode 100644 index 00000000..50376e08 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java @@ -0,0 +1,97 @@ +package at.asitplus.eidas.specific.connector.test.attributes; + +import at.asitplus.eidas.specific.connector.attributes.AuthBlockAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; +import at.gv.egiz.eaaf.core.impl.idp.auth.attributes.AbstractAttributeBuilderTest; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + + +import static at.asitplus.eidas.specific.connector.attributes.AuthBlockAttributeBuilder.EID_AUTHBLOCK_SIGNED_NAME; +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.SZR_AUTHBLOCK; + +@Slf4j +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/SpringTest-context_eaaf_core.xml") +public class AuthBlockAttributeBuilderTest extends AbstractAttributeBuilderTest { + + private final String JSW = + "eyJhbGciOiJQUzI1NiIsIng1dCNTMjU2IjoiTjBDZUJRdzlMX1BleEt6SlhVM2w2dkF1aExGb3hkWFlIUjNSX01ubTZnRSJ9.ImF2YWFz" + + "YmF2Ig.dpzCcHFlISXyKEZaXgvRj0ja1cenfMuy0VKwK_rmHZLkUCb58V4X5balpQduDTyRfTyFE0zmBjm8_cmDVNOYTIG4NsEtvY" + + "qW4ee9JH-VpkU0w5-7HTH81R3JOd9g7XaHGPXYyUuqceZQRmkl1Vw4HSsnIAT3bb0Di0us6zmFkOPmRtbXQAym_ygGFwTVGLskUTm" + + "epCxmDQC7OJoIV9oqDavLySP7Ram4NHfi043uF_DmBf6csTjmQu3g2vKJWwlkD8RXDzqksozO8fLDFyVWjA8G1IcvnuHDW1nTTkuG" + + "_fBIU6yBZ7kQe9vtjqKiGhGa1zD-F_Lem2zsY7d7dVUvyQ"; + private final IAttributeBuilder attrBuilde = new AuthBlockAttributeBuilder(); + + @Rule + public TestName mTestName = new TestName(); + + @Before + public void init() { + log.info("setting up"); + } + + @Test + public void okTest() { + log.info("starting: " + mTestName); + try { + final IAuthData authData = buildAuthData(); + ((AuthenticationData) authData).setGenericData(SZR_AUTHBLOCK, JSW); + + final String value = attrBuilde.build(spConfig, authData, gen); + + Assert.assertEquals("Authblock build wrong", JSW, value); + + } catch (final Exception e) { + Assert.assertNull("Attr. builder has an exception", e); + } + } + + + @Test + public void nullTest() { + log.info("starting: " + mTestName); + try { + final IAuthData authData = buildAuthData(); + ((AuthenticationData) authData).setGenericData(SZR_AUTHBLOCK, null); + + final String value = attrBuilde.build(spConfig, authData, gen); + Assert.fail("Attr. Builder provide no 'UnavailableAttributeException'"); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + EID_AUTHBLOCK_SIGNED_NAME, + ((UnavailableAttributeException) e).getAttributeName()); + } + } + + @Test + public void emptyTest() { + log.info("starting: " + mTestName); + try { + final IAuthData authData = buildAuthData(); + ((AuthenticationData) authData).setGenericData(SZR_AUTHBLOCK, ""); + + final String value = attrBuilde.build(spConfig, authData, gen); + Assert.fail("Attr. Builder provide no 'UnavailableAttributeException'"); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + EID_AUTHBLOCK_SIGNED_NAME, + ((UnavailableAttributeException) e).getAttributeName()); } + } +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java new file mode 100644 index 00000000..254efb59 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java @@ -0,0 +1,92 @@ +package at.asitplus.eidas.specific.connector.test.attributes; + +import at.asitplus.eidas.specific.connector.attributes.EidasBindAttributeBuilder; +import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; +import at.gv.egiz.eaaf.core.impl.idp.auth.attributes.AbstractAttributeBuilderTest; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.EIDAS_BIND; + + +@Slf4j +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/SpringTest-context_eaaf_core.xml") +public class EidasBindAttributeBuilderTest extends AbstractAttributeBuilderTest { + + private final IAttributeBuilder attrBuilde = new EidasBindAttributeBuilder(); + + @Rule + public TestName mTestName = new TestName(); + + @Before + public void init() { + log.info("setting up"); + } + + @Test + public void okTest() { + log.info("starting: " + mTestName); + try { + final IAuthData authData = buildAuthData(); + ((AuthenticationData) authData).setGenericData(EIDAS_BIND, "vuG8w29GT0"); + + final String value = attrBuilde.build(spConfig, authData, gen); + + Assert.assertEquals("eDIAS bind build wrong", "vuG8w29GT0", value); + + } catch (final Exception e) { + Assert.assertNull("Attr. builder has an exception", e); + } + } + + @Test + public void nullTest() { + log.info("starting: " + mTestName); + try { + final IAuthData authData = buildAuthData(); + ((AuthenticationData) authData).setGenericData(EIDAS_BIND, null); + + final String value = attrBuilde.build(spConfig, authData, gen); + Assert.fail("Attr. Builder provide no 'UnavailableAttributeException'"); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + ExtendedPvpAttributeDefinitions.EID_EIDBIND_NAME, + ((UnavailableAttributeException) e).getAttributeName()); + } + } + + @Test + public void emptyTest() { + log.info("starting: " + mTestName); + try { + final IAuthData authData = buildAuthData(); + ((AuthenticationData) authData).setGenericData(EIDAS_BIND, ""); + + final String value = attrBuilde.build(spConfig, authData, gen); + Assert.fail("Attr. Builder provide no 'UnavailableAttributeException'"); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + ExtendedPvpAttributeDefinitions.EID_EIDBIND_NAME, + ((UnavailableAttributeException) e).getAttributeName()); } + } + + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index af260528..f060a4cf 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -101,6 +101,7 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { @Autowired EaafKeyStoreFactory keyStoreFactory; + private static final String EID_STATUS = "urn:eidgvat:eid.status.eidas"; Pair ks; /* @@ -230,27 +231,24 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } if (eidMode.equals("new")) { - String keyAlias = pendingReq.getServiceProviderConfiguration().getConfigurationValue( MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME, ""); - String keyPw = pendingReq.getServiceProviderConfiguration() .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_PW, ""); + // get verschlüsselte Stammzahl String vsz = szrClient.getEncryptedStammzahl(personInfo); // build Keystore String pk64 = getPkFromKeystore(keyAlias, keyPw); + // get eIDAS bind + String signedEidasBind = szrClient.getBcBind(vsz, pk64, EID_STATUS); - String signedEidasBind = szrClient.getBcBind(vsz, pk64, "urn:eidgvat:eid.status.eidas"); - //TODO eidStatus as config? - - //build AuthBlock JWS + // build AuthBlock (JWS) ObjectMapper mapper = new ObjectMapper(); String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); - String jwsSignature = JoseUtils .createSignature(ks, keyAlias, keyPw.toCharArray(), jwsPayload, false, keyAlias); @@ -277,9 +275,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { bpk = szrClient .getBpk(personInfo, pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - basicConfig - .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")) - .get(0); + basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, + "no VKZ defined")).get(0); } else { log.debug("Calculating bPK from baseId ... "); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index c957e20c..d6bce8eb 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -143,7 +143,8 @@ public class SzrClientTest { when(szrMock.getBPKFromStammzahlEncrypted(anyList())) .thenReturn(Arrays.asList(result1)); -// szrMock.getStammzahlEncrypted() TODO ??? + String stammzahlEncrypted = szrMock.getStammzahlEncrypted(new PersonInfoType(), false); + } @Test -- cgit v1.2.3 From d40505ed35a8db7d242a8b218297e322350722b3 Mon Sep 17 00:00:00 2001 From: lalber Date: Thu, 5 Nov 2020 12:18:26 +0100 Subject: Test fixes --- .../modules/auth/eidas/v2/szr/SzrClient.java | 6 +- .../modules/auth/eidas/v2/test/SzrClientTest.java | 139 +++++++++++++-------- 2 files changed, 87 insertions(+), 58 deletions(-) diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java index d2ce2f5d..69b993a4 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/szr/SzrClient.java @@ -234,7 +234,7 @@ public class SzrClient { throw new SzrCommunicationException("ernb.02", new Object[]{e.getMessage()}, e); } - if (resp == null || StringUtils.isEmpty(resp)) { + if (StringUtils.isEmpty(resp)) { throw new SzrCommunicationException("ernb.01", new Object[]{"Stammzahl response empty"}); // TODO error handling } @@ -277,9 +277,9 @@ public class SzrClient { final SignContentResponseType resp = szr.signContent(req.isAppendCert(), req.getJWSHeaderParam(), req.getIn()); log.trace("Receive SZR response on bcBind siging operation "); - if (resp == null + if (resp == null || resp.getOut() == null || resp.getOut().isEmpty() - || resp.getOut().get(0).getValue() == null) { + || StringUtils.isEmpty(resp.getOut().get(0).getValue())) { throw new SzrCommunicationException("ernb.01", new Object[]{"BcBind response empty"}); } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index d6bce8eb..9709aeb9 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -105,10 +105,10 @@ public class SzrClientTest { private SZR szrMock = null; - + @Rule public SoapServiceRule soap = SoapServiceRule.newInstance(); - + /** * jUnit class initializer. * @@ -123,28 +123,38 @@ public class SzrClientTest { /** * Initialize jUnit test. - * */ @Before public void initializer() { if (szrMock == null) { szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); - - } + + } } - - + + @Test - public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception { + public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception, SzrCommunicationException { final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); szrResponse.getOut().add(result1); - when(szrMock.getBPKFromStammzahlEncrypted(anyList())) - .thenReturn(Arrays.asList(result1)); + result1.setKey(RandomStringUtils.randomAlphanumeric(20)); + + // when(szrMock.getBPKFromStammzahlEncrypted(anyList())) + // .thenReturn(Arrays.asList(result1)); + when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(result1.getKey()); - String stammzahlEncrypted = szrMock.getStammzahlEncrypted(new PersonInfoType(), false); + String stammzahlEncrypted = szrClient.getEncryptedStammzahl(new PersonInfoType()); + Assert.assertEquals("bcBind not match", result1.getKey(), stammzahlEncrypted); + + when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(null); + try { + stammzahlEncrypted = szrClient.getEncryptedStammzahl(new PersonInfoType()); + } catch (SzrCommunicationException e) { + Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); + } } @Test @@ -160,32 +170,61 @@ public class SzrClientTest { when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); - final String bcBind = szrClient.getBcBind( - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10)); + final String bcBind = szrClient + .getBcBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10)); Assert.assertNotNull("bcBind is null", bcBind); Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(null); + try { + szrClient + .getBcBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10)); + } catch (SzrCommunicationException e) { + Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); + } + + final SignContentEntry result2 = new SignContentEntry(); + final SignContentResponseType content1 = new SignContentResponseType(); + content1.getOut().add(result2); + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content1); + try { + szrClient + .getBcBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10)); + } catch (SzrCommunicationException e) { + Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); + } + + result2.setKey("bcBindReq"); + result2.setValue(""); + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content1); + try { + szrClient + .getBcBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10)); + } catch (SzrCommunicationException e) { + Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); + } } @Test - public void getIdentityLinkRawModeValidResponse() throws SZRException_Exception, EaafParserException, - NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException, - JAXBException { + public void getIdentityLinkRawModeValidResponse() + throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, + EidasSAuthenticationException, JAXBException { setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml"); try { log.debug("Starting connecting SZR Gateway"); - final IdentityLinkType result = szrClient.getIdentityLinkInRawMode( - getPersonInfo()); + final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(getPersonInfo()); Assert.assertNotNull(result); Assert.assertNotNull(result.getAssertion()); - final IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser((Element) result - .getAssertion()).parseIdentityLink(); + final IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser((Element) result.getAssertion()) + .parseIdentityLink(); Assert.assertNotNull(identityLink); System.out.println(identityLink.getSerializedSamlAssertion()); @@ -206,15 +245,14 @@ public class SzrClientTest { } @Test - public void getIdentityLinkRawModeErrorTravelerDocExists() throws SZRException_Exception, - EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, + public void getIdentityLinkRawModeErrorTravelerDocExists() + throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException, JAXBException, ParserConfigurationException, SAXException { setSzrExceptionIdentityLink("/data/szr/szr_resp_error_travelerdocexists.xml"); try { log.debug("Starting connecting SZR Gateway"); - szrClient.getIdentityLinkInRawMode( - getPersonInfo()); + szrClient.getIdentityLinkInRawMode(getPersonInfo()); Assert.fail(); } catch (final SzrCommunicationException e) { @@ -224,8 +262,7 @@ public class SzrClientTest { Assert.assertNotNull(((SOAPFaultException) e.getCause()).getFault()); checkElement("p344:F455", ((SOAPFaultException) e.getCause()).getFault().getFaultCode()); checkElement( - "The travel document you sent to insert a person already exists for another person. " - + "Either check the document or have the person altered accordingly", + "The travel document you sent to insert a person already exists for another person. " + "Either check the document or have the person altered accordingly", ((SOAPFaultException) e.getCause()).getFault().getFaultString()); } @@ -235,17 +272,15 @@ public class SzrClientTest { @Ignore @Test public void getBpkTest() throws SZRException_Exception, EidasSAuthenticationException { - final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, - basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, - "no VKZ defined")); + final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")); if (bPK.isEmpty()) { - throw new SzrCommunicationException("ernb.01", new Object[] { "bPK list is empty" }); + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); } for (final String b : bPK) { if (StringUtils.isEmpty(b)) { - throw new SzrCommunicationException("ernb.01", new Object[] { "bPK is null or empty" }); + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); } } @@ -257,29 +292,24 @@ public class SzrClientTest { } - private void setSzrResponseIdentityLink(String responseXmlPath) throws JAXBException, - SZRException_Exception { - final JAXBContext jaxbContext = JAXBContext.newInstance( - szrservices.ObjectFactory.class, - org.w3._2001._04.xmldsig_more.ObjectFactory.class, - org.w3._2000._09.xmldsig.ObjectFactory.class, - at.gv.e_government.reference.namespace.persondata._20020228.ObjectFactory.class); + private void setSzrResponseIdentityLink(String responseXmlPath) throws JAXBException, SZRException_Exception { + final JAXBContext jaxbContext = JAXBContext + .newInstance(szrservices.ObjectFactory.class, org.w3._2001._04.xmldsig_more.ObjectFactory.class, + org.w3._2000._09.xmldsig.ObjectFactory.class, + at.gv.e_government.reference.namespace.persondata._20020228.ObjectFactory.class); final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); final GetIdentityLinkEidasResponse szrResponse = (GetIdentityLinkEidasResponse) jaxbUnmarshaller .unmarshal(this.getClass().getResourceAsStream(responseXmlPath)); - when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenReturn(szrResponse - .getGetIdentityLinkReturn()); + when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenReturn(szrResponse.getGetIdentityLinkReturn()); } - private void setSzrExceptionIdentityLink(String responseXmlPath) throws JAXBException, - ParserConfigurationException, SAXException, IOException, SZRException_Exception { - final Element detailerror = DomUtils.parseXmlNonValidating(this.getClass().getResourceAsStream( - responseXmlPath)); + private void setSzrExceptionIdentityLink(String responseXmlPath) + throws JAXBException, ParserConfigurationException, SAXException, IOException, SZRException_Exception { + final Element detailerror = DomUtils.parseXmlNonValidating(this.getClass().getResourceAsStream(responseXmlPath)); final javax.xml.namespace.QName qName = new javax.xml.namespace.QName("urn:SZRServices", "F455", "p344"); final SoapFault fault = new SoapFault( - "The travel document you sent to insert a person already exists for another person. " - + "Either check the document or have the person altered accordingly", + "The travel document you sent to insert a person already exists for another person. " + "Either check the document or have the person altered accordingly", qName); fault.setRole("urn:SZRServices"); fault.setDetail(detailerror); @@ -295,7 +325,7 @@ public class SzrClientTest { return hashBase64; } catch (final Exception ex) { - throw new EidasSAuthenticationException("internal.03", new Object[] {}, ex); + throw new EidasSAuthenticationException("internal.03", new Object[]{}, ex); } } @@ -311,8 +341,7 @@ public class SzrClientTest { personInfo.setTravelDocument(eDocument); // parse some eID attributes - final Triple eIdentifier = - EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); + final Triple eIdentifier = EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); final String uniqueId = createHashFromUniqueId(eIdentifier.getThird()); final String citizenCountry = eIdentifier.getFirst(); @@ -324,9 +353,9 @@ public class SzrClientTest { eDocument.setDocumentNumber(uniqueId); // eID document information - eDocument.setDocumentType(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, - Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); + eDocument.setDocumentType(basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, + Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); return personInfo; } -- cgit v1.2.3 From f358f3ba6a24d5e9575b3fd63e3fbfe8848b63c4 Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 6 Nov 2020 16:28:26 +0100 Subject: some improvements --- .../builder/AuthenticationDataBuilder.java | 8 +- .../test/AuthenticationDataBuilderTest.java | 4 +- .../specific/connector/MsEidasNodeConstants.java | 18 +++-- .../eidas/v2/tasks/CreateIdentityLinkTask.java | 65 ++++++++++------- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 85 +++++++++++++--------- .../resources/config/junit_config_3.properties | 11 ++- 6 files changed, 115 insertions(+), 76 deletions(-) diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java index 42163097..ef1a1f2b 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java @@ -56,13 +56,11 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder final IAuthProcessDataContainer authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); AuthenticationData authData = new AuthenticationData(); - String eidMode = pendingReq.getServiceProviderConfiguration() - .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); - - if (eidMode.equals("new")) { + boolean isEidModeNew = pendingReq.getServiceProviderConfiguration() + .isConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE, false); + if (isEidModeNew) { authData = (AuthenticationData) super.buildAuthenticationData(pendingReq); - } else { try { generateDeprecatedBasicAuthData(authData, pendingReq, authProcessData); diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java index 4ae2a34d..78d2ee1a 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java @@ -31,6 +31,8 @@ import org.springframework.web.context.request.ServletRequestAttributes; import java.util.HashMap; import java.util.Map; +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext.xml", "/SpringTest_connector.beans.xml", @@ -72,7 +74,7 @@ public class AuthenticationDataBuilderTest { final Map spConfig = new HashMap<>(); spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); - spConfig.put("eidMode", "new"); + spConfig.put(PROP_CONFIG_SP_NEW_EID_MODE, "true"); oaParam = new DummySpConfiguration(spConfig, basicConfig); pendingReq = new TestRequestImpl(); diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java index d9aac126..10ec9791 100644 --- a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java @@ -86,6 +86,15 @@ public class MsEidasNodeConstants { public static final String PROP_EIDAS_REQUEST_LOA_MINIMUM_LEVEL = "auth.eIDAS.node_v2.loa.requested.minimum"; + public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD = + "auth.eIDAS.authblock.keystore.password"; + public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME = + "auth.eIDAS.authblock.keystore.friendlyName"; + public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PATH = + "auth.eIDAS.authblock.keystore.path"; + public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_TYPE = + "auth.eIDAS.authblock.keystore.type"; + public static final String PROP_CONFIG_SP_LIST_PREFIX = "sp."; public static final String PROP_CONFIG_SP_UNIQUEIDENTIFIER = EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER; @@ -94,12 +103,9 @@ public class MsEidasNodeConstants { public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE = "pvp2.metadata.truststore"; public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE_PASSWORD = "pvp2.metadata.truststore.password"; - public static final String PROP_CONFIG_SP_EID_MODE = - "eidMode"; - public static final String PROP_CONFIG_SP_AUTHBLOCK_PW = - "authblock.truststore.password"; - public static final String PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME = - "authblock.truststore.friendlyName"; + public static final String PROP_CONFIG_SP_NEW_EID_MODE = + "newEidMode"; + public static final String PROP_CONFIG_SP_POLICY_ALLOWED_TARGETS = "policy.allowed.requested.targets"; public static final String PROP_CONFIG_SP_POLICY_BASEIDTRANSFER_RESTRICTION = "policy.hasBaseIdTransferRestriction"; diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index f060a4cf..8626c709 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -60,7 +60,6 @@ import eu.eidas.auth.commons.attribute.AttributeValue; import eu.eidas.auth.commons.light.ILightResponse; import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; import lombok.extern.slf4j.Slf4j; -import lombok.val; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; @@ -77,6 +76,7 @@ import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Provider; +import java.security.PublicKey; import java.util.Base64; import java.util.HashMap; import java.util.List; @@ -102,7 +102,6 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { EaafKeyStoreFactory keyStoreFactory; private static final String EID_STATUS = "urn:eidgvat:eid.status.eidas"; - Pair ks; /* * (non-Javadoc) @@ -119,8 +118,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); final ILightResponse eidasResponse = authProcessData .getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE, ILightResponse.class); - String eidMode = pendingReq.getServiceProviderConfiguration() - .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE, "old"); + boolean isNewEidMode = pendingReq.getServiceProviderConfiguration() + .isConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE, false); final Map simpleAttrMap = convertEidasAttrToSimpleMap( @@ -230,17 +229,31 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - if (eidMode.equals("new")) { - String keyAlias = pendingReq.getServiceProviderConfiguration().getConfigurationValue( - MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME, ""); - String keyPw = pendingReq.getServiceProviderConfiguration() - .getConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_PW, ""); + if (isNewEidMode) { + + // read Connector wide config data TODO connector wide! + String keyStoreAlias = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME); + String keyStorePw = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD); + String keyStorePath = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PATH); + String keyStoreType = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_TYPE); + // get verschlüsselte Stammzahl String vsz = szrClient.getEncryptedStammzahl(personInfo); // build Keystore - String pk64 = getPkFromKeystore(keyAlias, keyPw); + Pair keystoreProvider = initKeystore(keyStoreAlias, keyStorePw, keyStorePath, + keyStoreType); + + // get pubKey + PublicKey publicKey = keystoreProvider.getFirst().getCertificate(keyStoreAlias).getPublicKey(); + + // encode pubKey base64 + String pk64 = Base64.getEncoder().encodeToString(publicKey.getEncoded()); // get eIDAS bind String signedEidasBind = szrClient.getBcBind(vsz, pk64, EID_STATUS); @@ -250,7 +263,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); String jwsSignature = JoseUtils - .createSignature(ks, keyAlias, keyPw.toCharArray(), jwsPayload, false, keyAlias); + .createSignature(keystoreProvider, keyStoreAlias, keyStorePw.toCharArray(), jwsPayload, false, + keyStoreAlias); authProcessData.setGenericDataToSession(Constants.SZR_AUTHBLOCK, jwsSignature); authProcessData.setGenericDataToSession(Constants.EIDAS_BIND, signedEidasBind); @@ -275,8 +289,9 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { bpk = szrClient .getBpk(personInfo, pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, - "no VKZ defined")).get(0); + basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")) + .get(0); } else { log.debug("Calculating bPK from baseId ... "); @@ -292,7 +307,7 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - if (eidMode.equals("new")) { + if (isNewEidMode) { authProcessData.setForeigner(true); authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, EidasResponseUtils .parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)) @@ -305,7 +320,8 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { throw new SzrCommunicationException("ernb.00", null); } - revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_IDL_RECEIVED, + revisionsLogger.logEvent(pendingReq, + MsConnectorEventCodes.SZR_IDL_RECEIVED, identityLink.getSamlAssertion() .getAttribute(SimpleIdentityLinkAssertionParser.ASSERTIONID)); @@ -348,18 +364,17 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } - private String getPkFromKeystore(String keyAlias, String keyPw) throws EaafException, KeyStoreException { - KeyStoreConfiguration configuration = new KeyStoreConfiguration(); + private Pair initKeystore(String keyAlias, String keyPw, String path, String type) + throws EaafException, KeyStoreException { + KeyStoreConfiguration keyStoreConfiguration = new KeyStoreConfiguration(); final String current = new java.io.File(".").toURI().toString(); - configuration.setSoftKeyStoreFilePath(current + "src/test/resources/keystore/teststore.jks"); - configuration.setSoftKeyStorePassword(keyPw); //TODO from config - configuration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.JKS); - configuration.setFriendlyName(keyAlias); - configuration.setKeyStoreName(keyAlias); - ks = keyStoreFactory.buildNewKeyStore(configuration); - val publicKey = ks.getFirst().getCertificate(keyAlias).getPublicKey(); - return Base64.getEncoder().encodeToString(publicKey.getEncoded()); + keyStoreConfiguration.setSoftKeyStoreFilePath(current + path); + keyStoreConfiguration.setSoftKeyStorePassword(keyPw); + keyStoreConfiguration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.fromString(type)); + keyStoreConfiguration.setFriendlyName(keyAlias); + keyStoreConfiguration.setKeyStoreName(keyAlias); + return keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); } private String extendBpkByPrefix(String bpk, String type) { diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index 00e01a2c..888b7631 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -1,8 +1,8 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME; -import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_PW; -import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_EID_MODE; +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME; +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD; +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; import static org.mockito.ArgumentMatchers.any; import static org.powermock.api.mockito.PowerMockito.when; @@ -69,8 +69,8 @@ public class CreateIdentityLinkTaskEidNewTest { @Autowired(required = true) private CreateIdentityLinkTask task; -// @Autowired(required = true) -// private FinalizeAuthenticationTask authTask; + // @Autowired(required = true) + // private FinalizeAuthenticationTask authTask; @Autowired(required = true) private DummySpecificCommunicationService commService; @Autowired(required = true) @@ -87,7 +87,7 @@ public class CreateIdentityLinkTaskEidNewTest { private static final String PW = "f/+saJBc3a}*/T^s"; private static final String ALIAS = "connectorkeypair"; - + @Rule public final SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -99,8 +99,7 @@ public class CreateIdentityLinkTaskEidNewTest { @BeforeClass public static void classInitializer() throws IOException { final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current - + "src/test/resources/config/junit_config_3.properties"); + System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_3.properties"); } @@ -118,18 +117,17 @@ public class CreateIdentityLinkTaskEidNewTest { final Map spConfig = new HashMap<>(); spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); - spConfig.put(PROP_CONFIG_SP_EID_MODE, "new"); - spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_PW, PW); - spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_FRIENDLYNAME, ALIAS); + spConfig.put(PROP_CONFIG_SP_NEW_EID_MODE, "true"); + spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD, PW); + spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME, ALIAS); oaParam = new DummySpConfiguration(spConfig, basicConfig); pendingReq = new TestRequestImpl(); AuthenticationResponse response = buildDummyAuthResponse(); - - - pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); pendingReq.setSpConfig(oaParam); pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); pendingReq.setAuthUrl("http://test.com/"); @@ -143,33 +141,48 @@ public class CreateIdentityLinkTaskEidNewTest { @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { - AttributeDefinition attributeDef = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER) - .nameUri(new URI("ad", "sd", "ff")).personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "af")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - AttributeDefinition attributeDef2 = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME) - .nameUri(new URI("ad", "sd", "fff")).personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "aff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - AttributeDefinition attributeDef3 = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME) - .nameUri(new URI("ad", "sd", "ffff")).personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "afff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + AttributeDefinition attributeDef = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER) + .nameUri(new URI("ad", "sd", "ff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "af")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") + .build(); + AttributeDefinition attributeDef2 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME) + .nameUri(new URI("ad", "sd", "fff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "aff")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") + .build(); + AttributeDefinition attributeDef3 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME) + .nameUri(new URI("ad", "sd", "ffff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "afff")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") + .build(); AttributeDefinition attributeDef4 = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH) - .nameUri(new URI("ad", "sd", "fffff")).personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "affff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); + .nameUri(new URI("ad", "sd", "fffff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "affff")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller") + .build(); - ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder().put(attributeDef, "de/st/" + RandomStringUtils.randomNumeric(64)) - .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) - .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)) - .put(attributeDef4, "2001-01-01") - .build(); + ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder().put(attributeDef, "de/st/" + RandomStringUtils + .randomNumeric(64)).put(attributeDef2, RandomStringUtils.randomAlphabetic(10)).put(attributeDef3, + RandomStringUtils + .randomAlphabetic(10)) + .put(attributeDef4, "2001-01-01").build(); val b = new AuthenticationResponse.Builder(); - return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf") - .subjectNameIdFormat("afaf").attributes(attributeMap).build(); + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf") + .attributes(attributeMap).build(); } @Test diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties index 33207118..79352734 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_3.properties @@ -47,6 +47,12 @@ eidas.ms.auth.eIDAS.szrclient.timeout.connection=15 eidas.ms.auth.eIDAS.szrclient.timeout.response=30 eidas.ms.auth.eIDAS.szrclient.params.vkz= +eidas.ms.auth.eIDAS.authblock.keystore.password=f/+saJBc3a}*/T^s +eidas.ms.auth.eIDAS.authblock.keystore.friendlyName=connectorkeypair +eidas.ms.auth.eIDAS.authblock.keystore.path=src/test/resources/keystore/teststore.jks +eidas.ms.auth.eIDAS.authblock.keystore.type=jks + + eidas.ms.auth.eIDAS.szrclient.params.useSZRForbPKCalculation=false @@ -93,9 +99,8 @@ eidas.ms.pvp2.metadata.validity=24 eidas.ms.sp.0.uniqueID= eidas.ms.sp.0.pvp2.metadata.truststore= eidas.ms.sp.0.pvp2.metadata.truststore.password= -eidas.ms.sp.0.eidMode=new -eidas.ms.sp.0.authblock.truststore.password=f/+saJBc3a}*/T^s -eidas.ms.sp.0.authblock.truststore.friendlyName=connectorkeypair +eidas.ms.sp.0.newEidMode=true + #eidas.ms.sp.0.friendlyName= #eidas.ms.sp.0.pvp2.metadata.url= -- cgit v1.2.3 From 57d813b9cfbbd231a2e6f9d47169b31435d1d6c0 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Sat, 7 Nov 2020 18:21:49 +0100 Subject: code clean-up and first jUnit test modifications for CreateIdentityLink task --- basicConfig/default_config.properties | 9 + basicConfig/keys/teststore.jks | Bin 0 -> 2028 bytes .../connector/provider/PvpMetadataProvider.java | 7 + .../specific/connector/MsEidasNodeConstants.java | 23 +- .../eidas/v2/service/AuthBlockSigningService.java | 147 ++++++ .../eidas/v2/tasks/CreateIdentityLinkTask.java | 507 +++++++++++---------- .../src/main/resources/eidas_v2_auth.beans.xml | 3 + .../eidas/v2/test/SzrClientTestProduction.java | 2 +- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 204 ++++++--- .../resources/SpringTest-context_tasks_test.xml | 3 + .../resources/config/junit_config_1.properties | 8 + .../resources/config/junit_config_2.properties | 8 + .../resources/config/junit_config_3.properties | 4 +- pom.xml | 2 +- 14 files changed, 595 insertions(+), 332 deletions(-) create mode 100644 basicConfig/keys/teststore.jks create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java diff --git a/basicConfig/default_config.properties b/basicConfig/default_config.properties index dda5144e..2e0aebcc 100644 --- a/basicConfig/default_config.properties +++ b/basicConfig/default_config.properties @@ -50,6 +50,15 @@ eidas.ms.auth.eIDAS.szrclient.params.vkz= eidas.ms.auth.eIDAS.szrclient.params.useSZRForbPKCalculation=false +## E-AuthBlock configuration +eidas.ms.auth.eIDAS.authblock.keystore.type=jks +eidas.ms.auth.eIDAS.authblock.keystore.path=keys/teststore.jks +eidas.ms.auth.eIDAS.authblock.keystore.password=f/+saJBc3a}*/T^s +eidas.ms.auth.eIDAS.authblock.keystore.name= +eidas.ms.auth.eIDAS.authblock.key.alias=connectorkeypair +eidas.ms.auth.eIDAS.authblock.key.password=f/+saJBc3a}*/T^s + + #Raw eIDAS Id data storage eidas.ms.auth.eIDAS.szrclient.workarounds.eidmapping.revisionlog.active=true diff --git a/basicConfig/keys/teststore.jks b/basicConfig/keys/teststore.jks new file mode 100644 index 00000000..fcc6400c Binary files /dev/null and b/basicConfig/keys/teststore.jks differ diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PvpMetadataProvider.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PvpMetadataProvider.java index 651b7b78..8dbb74c7 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PvpMetadataProvider.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PvpMetadataProvider.java @@ -173,4 +173,11 @@ public class PvpMetadataProvider extends AbstractChainingMetadataProvider { return "Service-provider chainging metadata provider"; } + + @Override + public void doDestroy() { + this.fullyDestroy(); + + } + } diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java index 10ec9791..b1ef799f 100644 --- a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MsEidasNodeConstants.java @@ -86,15 +86,22 @@ public class MsEidasNodeConstants { public static final String PROP_EIDAS_REQUEST_LOA_MINIMUM_LEVEL = "auth.eIDAS.node_v2.loa.requested.minimum"; - public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD = - "auth.eIDAS.authblock.keystore.password"; - public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME = - "auth.eIDAS.authblock.keystore.friendlyName"; - public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PATH = - "auth.eIDAS.authblock.keystore.path"; - public static final String PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_TYPE = - "auth.eIDAS.authblock.keystore.type"; + public static final String PROP_CONFIG_AUTHBLOCK_KEYSTORE_TYPE = + "auth.eIDAS.authblock.keystore.type"; + public static final String PROP_CONFIG_AUTHBLOCK_KEYSTORE_PATH = + "auth.eIDAS.authblock.keystore.path"; + public static final String PROP_CONFIG_AUTHBLOCK_KEYSTORE_PASSWORD = + "auth.eIDAS.authblock.keystore.password"; + public static final String PROP_CONFIG_AUTHBLOCK_KEYSTORE_NAME = + "auth.eIDAS.authblock.keystore.name"; + public static final String PROP_CONFIG_AUTHBLOCK_KEY_ALIAS = + "auth.eIDAS.authblock.key.alias"; + public static final String PROP_CONFIG_AUTHBLOCK_KEY_PASSWORD = + "auth.eIDAS.authblock.key.password"; + + + public static final String PROP_CONFIG_SP_LIST_PREFIX = "sp."; public static final String PROP_CONFIG_SP_UNIQUEIDENTIFIER = EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER; diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java new file mode 100644 index 00000000..30d255b9 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java @@ -0,0 +1,147 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.service; + +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.Provider; +import java.security.cert.X509Certificate; +import java.util.Base64; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.jose4j.lang.JoseException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.JoseUtils; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exception.EaafKeyAccessException; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreUtils; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import lombok.extern.slf4j.Slf4j; + +/** + * Service to build and sign AuthBlock's for E-ID system. + * + * @author tlenz + * + */ +@Slf4j +@Service("authBlockSigningService") +public class AuthBlockSigningService { + + private static final String KEYSTORE_FRIENDLYNAME = "AuthBlock_Signing"; + + private static ObjectMapper mapper = new ObjectMapper(); + + @Autowired + IConfiguration basicConfig; + + @Autowired + EaafKeyStoreFactory keyStoreFactory; + + + private Pair keyStore; + + /** + * Build and sign an AuthBlock for E-ID system. + * + * @param dataToSign data that should be added into AuthBlock + * @return serialized JWS + * @throws JsonProcessingException In case of a AuthBlock generation error + * @throws JoseException In case of a JWS signing error + * @throws EaafException In case of a KeyStore or Key error + */ + public String buildSignedAuthBlock(String dataToSign) + throws JsonProcessingException, EaafException, JoseException { + log.debug("Building and sign authBlock with data: {}", dataToSign); + + // build AuthBlock + String jwsPayload = mapper.writeValueAsString(dataToSign); + + //sign JWS + return JoseUtils + .createSignature(keyStore, getKeyAlias(), getKeyPassword(), jwsPayload, false, + KEYSTORE_FRIENDLYNAME); + } + + + /** + * Get the Base64 encoded PublicKey that is used to sign the AuthBlock. + * + * @return Base64 encoded PublicKey + * @throws EaafKeyAccessException In case of an unknown or invalid key + */ + public String getBase64EncodedPublicKey() throws EaafKeyAccessException { + Pair keyPair = EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore.getFirst(), getKeyAlias(), getKeyPassword(), true, KEYSTORE_FRIENDLYNAME); + return Base64.getEncoder().encodeToString(keyPair.getSecond()[0].getPublicKey().getEncoded()); + + } + + @PostConstruct + private void initialize() throws KeyStoreException, EaafException { + log.debug("Initializing AuthBlock signing service ... "); + // read Connector wide config data TODO connector wide! + String keyStoreName = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_NAME); + String keyStorePw = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PASSWORD); + String keyStorePath = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PATH); + String keyStoreType = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_TYPE); + + + //build new KeyStore configuration + KeyStoreConfiguration keyStoreConfiguration = new KeyStoreConfiguration(); + keyStoreConfiguration.setFriendlyName(KEYSTORE_FRIENDLYNAME); + + keyStoreConfiguration.setSoftKeyStoreFilePath(keyStorePath); + keyStoreConfiguration.setSoftKeyStorePassword(keyStorePw); + keyStoreConfiguration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.fromString(keyStoreType)); + keyStoreConfiguration.setKeyStoreName(keyStoreName); + + //validate KeyStore configuration + keyStoreConfiguration.validate(); + + //validate key alias + if (StringUtils.isEmpty(getKeyAlias())) { + throw new EaafConfigurationException("config.08", + new Object[] {MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEY_ALIAS}); + + } + + //build new KeyStore based on configuration + keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); + + log.info("AuthBlock signing-service successful initialized"); + + } + + private char[] getKeyPassword() { + final String value = basicConfig.getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEY_PASSWORD); + if (value != null) { + return value.trim().toCharArray(); + } + + return null; + + } + + + private String getKeyAlias() { + return basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEY_ALIAS); + + } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index 8626c709..1ffd56e4 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -23,16 +23,37 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + import at.asitplus.eidas.specific.connector.MsConnectorEventCodes; import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.ErnbEidData; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasAttributeException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicationException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.AuthBlockSigningService; import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.ICcSpecificEidProcessingService; import at.asitplus.eidas.specific.modules.auth.eidas.v2.szr.SzrClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.EidasResponseUtils; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.JoseUtils; import at.gv.e_government.reference.namespace.persondata._20020228.AlternativeNameType; import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType; @@ -43,8 +64,6 @@ import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -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.data.Pair; import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; @@ -52,36 +71,16 @@ import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egiz.eaaf.core.impl.utils.DomUtils; import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import eu.eidas.auth.commons.attribute.AttributeDefinition; import eu.eidas.auth.commons.attribute.AttributeValue; import eu.eidas.auth.commons.light.ILightResponse; import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; +import lombok.Data; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.w3c.dom.Element; -import org.w3c.dom.Node; import szrservices.IdentityLinkType; import szrservices.PersonInfoType; import szrservices.TravelDocumentType; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.InputStream; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.Provider; -import java.security.PublicKey; -import java.util.Base64; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Task that creates the IdentityLink for an eIDAS authenticated person. * @@ -97,12 +96,12 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { private SzrClient szrClient; @Autowired private ICcSpecificEidProcessingService eidPostProcessor; - + @Autowired - EaafKeyStoreFactory keyStoreFactory; + private AuthBlockSigningService authBlockSigner; private static final String EID_STATUS = "urn:eidgvat:eid.status.eidas"; - + /* * (non-Javadoc) * @@ -118,164 +117,57 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); final ILightResponse eidasResponse = authProcessData .getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE, ILightResponse.class); - boolean isNewEidMode = pendingReq.getServiceProviderConfiguration() - .isConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE, false); - final Map simpleAttrMap = convertEidasAttrToSimpleMap( eidasResponse.getAttributes().getAttributeMap()); - IIdentityLink identityLink = null; - String bpk = null; - // post-process eIDAS attributes final ErnbEidData eidData = eidPostProcessor.postProcess(simpleAttrMap); // write MDS into technical log and revision log writeMdsLogInformation(eidData); - // connect SZR-Gateway + //build IdentityLink or VSZ and eidasBind if (basicConfig.getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USEDUMMY, false)) { - log.warn("SZR-Dummy IS ACTIVE! IdentityLink is NOT VALID!!!!"); - // create fake IdL - // - fetch IdL template from resources - final InputStream s = CreateIdentityLinkTask.class - .getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); - final Element idlTemplate = DomUtils.parseXmlValidating(s); - - identityLink = new SimpleIdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); - - // replace data - final Element idlassertion = identityLink.getSamlAssertion(); - - // - set fake baseID; - final Node prIdentification = XPathUtils - .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(eidData.getPseudonym()); - - // - set last name - final Node prFamilyName = XPathUtils - .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); - prFamilyName.getFirstChild().setNodeValue(eidData.getFamilyName()); - - // - set first name - final Node prGivenName = XPathUtils - .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); - prGivenName.getFirstChild().setNodeValue(eidData.getGivenName()); - - // - set date of birth - final Node prDateOfBirth = XPathUtils - .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); - - prDateOfBirth.getFirstChild().setNodeValue(eidData.getFormatedDateOfBirth()); - - identityLink = new SimpleIdentityLinkAssertionParser(idlassertion).parseIdentityLink(); - - new BpkBuilder(); - final Pair bpkCalc = BpkBuilder - .generateAreaSpecificPersonIdentifier(identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), - pendingReq.getServiceProviderConfiguration() - .getAreaSpecificTargetIdentifier()); - bpk = bpkCalc.getFirst(); - + SzrResultHolder idlResult = createDummyIdentityLinkForTestDeployment(eidData); + //inject personal-data into session + authProcessData.setIdentityLink(idlResult.getIdentityLink()); + + // set bPK and bPKType into auth session + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.BPK_NAME, extendBpkByPrefix( + idlResult.getBpK(), pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier())); + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); + } else { - // contact SZR Gateway - log.debug("Starting connecting SZR Gateway"); - final PersonInfoType personInfo = new PersonInfoType(); - final PersonNameType personName = new PersonNameType(); - final PhysicalPersonType naturalPerson = new PhysicalPersonType(); - final TravelDocumentType eDocument = new TravelDocumentType(); - - naturalPerson.setName(personName); - personInfo.setPerson(naturalPerson); - personInfo.setTravelDocument(eDocument); - - // person information - personName.setFamilyName(eidData.getFamilyName()); - personName.setGivenName(eidData.getGivenName()); - naturalPerson.setDateOfBirth(eidData.getFormatedDateOfBirth()); - eDocument.setIssuingCountry(eidData.getCitizenCountryCode()); - eDocument.setDocumentNumber(eidData.getPseudonym()); - - // eID document information - eDocument.setDocumentType(basicConfig - .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, - Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); - - // set PlaceOfBirth if available - if (eidData.getPlaceOfBirth() != null) { - log.trace("Find 'PlaceOfBirth' attribute: " + eidData.getPlaceOfBirth()); - if (basicConfig - .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETPLACEOFBIRTHIFAVAILABLE, - true)) { - naturalPerson.setPlaceOfBirth(eidData.getPlaceOfBirth()); - log.trace("Adding 'PlaceOfBirth' to ERnB request ... "); - - } - } - - // set BirthName if available - if (eidData.getBirthName() != null) { - log.trace("Find 'BirthName' attribute: " + eidData.getBirthName()); - if (basicConfig - .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETBIRTHNAMEIFAVAILABLE, - true)) { - final AlternativeNameType alternativeName = new AlternativeNameType(); - naturalPerson.setAlternativeName(alternativeName); - alternativeName.setFamilyName(eidData.getBirthName()); - log.trace("Adding 'BirthName' to ERnB request ... "); - - } - } - - if (isNewEidMode) { - - // read Connector wide config data TODO connector wide! - String keyStoreAlias = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME); - String keyStorePw = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD); - String keyStorePath = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PATH); - String keyStoreType = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_TYPE); - - - // get verschlüsselte Stammzahl + //build SZR request from eIDAS data + final PersonInfoType personInfo = generateSzrRequest(eidData); + + //request SZR based on IDL or E-ID mode + if (pendingReq.getServiceProviderConfiguration() + .isConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE, false)) { + + // get encrypted baseId String vsz = szrClient.getEncryptedStammzahl(personInfo); - - // build Keystore - Pair keystoreProvider = initKeystore(keyStoreAlias, keyStorePw, keyStorePath, - keyStoreType); - - // get pubKey - PublicKey publicKey = keystoreProvider.getFirst().getCertificate(keyStoreAlias).getPublicKey(); - - // encode pubKey base64 - String pk64 = Base64.getEncoder().encodeToString(publicKey.getEncoded()); - + // get eIDAS bind - String signedEidasBind = szrClient.getBcBind(vsz, pk64, EID_STATUS); - - // build AuthBlock (JWS) - ObjectMapper mapper = new ObjectMapper(); - String jwsPayload = mapper.writeValueAsString(pendingReq.getUniqueTransactionIdentifier()); - - String jwsSignature = JoseUtils - .createSignature(keystoreProvider, keyStoreAlias, keyStorePw.toCharArray(), jwsPayload, false, - keyStoreAlias); - + String signedEidasBind = szrClient.getBcBind(vsz, + authBlockSigner.getBase64EncodedPublicKey(), + EID_STATUS); + + //get signed AuthBlock + String jwsSignature = authBlockSigner.buildSignedAuthBlock(pendingReq.getUniqueTransactionIdentifier()); + + //inject personal-data into session authProcessData.setGenericDataToSession(Constants.SZR_AUTHBLOCK, jwsSignature); authProcessData.setGenericDataToSession(Constants.EIDAS_BIND, signedEidasBind); + } else { - - final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(personInfo); - - final Element idlFromSzr = (Element) result.getAssertion(); - identityLink = new SimpleIdentityLinkAssertionParser(idlFromSzr).parseIdentityLink(); - - // write ERnB inputdata into revisionlog + //request SZR + SzrResultHolder idlResult = requestSzrForIdentityLink(personInfo); + + // write ERnB input-data into revision-log if (basicConfig.getBasicConfigurationBoolean( Constants.CONIG_PROPS_EIDAS_SZRCLIENT_WORKAROUND_REVISIONLOGDATASTORE_ACTIVE, false)) { revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_ERNB_EIDAS_RAW_ID, @@ -283,100 +175,158 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_ERNB_EIDAS_ERNB_ID, eidData.getPseudonym()); } - - // get bPK from SZR - if (basicConfig - .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { - bpk = szrClient - .getBpk(personInfo, pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - basicConfig - .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")) - .get(0); - - } else { - log.debug("Calculating bPK from baseId ... "); - new BpkBuilder(); - final Pair bpkCalc = BpkBuilder - .generateAreaSpecificPersonIdentifier(identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), - pendingReq.getServiceProviderConfiguration() - .getAreaSpecificTargetIdentifier()); - bpk = bpkCalc.getFirst(); - - } + + //check result-data and write revision-log based on current state + checkStateAndWriteRevisionLog(idlResult); + + + //inject personal-data into session + authProcessData.setIdentityLink(idlResult.getIdentityLink()); + + // set bPK and bPKType into auth session + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.BPK_NAME, extendBpkByPrefix( + idlResult.getBpK(), pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier())); + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); + } } + + //add generic info's into session + authProcessData.setForeigner(true); + authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, EidasResponseUtils + .parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)) + .getFirst()); + authProcessData.setQaaLevel(eidasResponse.getLevelOfAssurance()); + + // store pending-request + requestStoreage.storePendingRequest(pendingReq); + + + } catch (final EidasAttributeException e) { + throw new TaskExecutionException(pendingReq, "Minimum required eIDAS attributeset not found.", e); - if (isNewEidMode) { - authProcessData.setForeigner(true); - authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, EidasResponseUtils - .parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)) - .getFirst()); - authProcessData.setQaaLevel(eidasResponse.getLevelOfAssurance()); + } catch (final EaafException e) { + throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); - } else { - if (identityLink == null) { - log.error("ERnB did not return an identity link."); - throw new SzrCommunicationException("ernb.00", null); + } catch (final Exception e) { + log.error("IdentityLink generation for foreign person FAILED.", e); + throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); - } - revisionsLogger.logEvent(pendingReq, - MsConnectorEventCodes.SZR_IDL_RECEIVED, - identityLink.getSamlAssertion() - .getAttribute(SimpleIdentityLinkAssertionParser.ASSERTIONID)); + } + } - if (bpk == null) { - log.error("ERnB did not return a bPK for target: " + pendingReq.getServiceProviderConfiguration() - .getAreaSpecificTargetIdentifier()); - throw new SzrCommunicationException("ernb.01", null); + private PersonInfoType generateSzrRequest(ErnbEidData eidData) { + log.debug("Starting connecting SZR Gateway"); + final PersonInfoType personInfo = new PersonInfoType(); + final PersonNameType personName = new PersonNameType(); + final PhysicalPersonType naturalPerson = new PhysicalPersonType(); + final TravelDocumentType eDocument = new TravelDocumentType(); + + naturalPerson.setName(personName); + personInfo.setPerson(naturalPerson); + personInfo.setTravelDocument(eDocument); + + // person information + personName.setFamilyName(eidData.getFamilyName()); + personName.setGivenName(eidData.getGivenName()); + naturalPerson.setDateOfBirth(eidData.getFormatedDateOfBirth()); + eDocument.setIssuingCountry(eidData.getCitizenCountryCode()); + eDocument.setDocumentNumber(eidData.getPseudonym()); + + // eID document information + eDocument.setDocumentType(basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, + Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); + + // set PlaceOfBirth if available + if (eidData.getPlaceOfBirth() != null) { + log.trace("Find 'PlaceOfBirth' attribute: " + eidData.getPlaceOfBirth()); + if (basicConfig + .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETPLACEOFBIRTHIFAVAILABLE, + true)) { + naturalPerson.setPlaceOfBirth(eidData.getPlaceOfBirth()); + log.trace("Adding 'PlaceOfBirth' to ERnB request ... "); - } - revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_BPK_RECEIVED); + } + } - log.debug("ERnB communication was successfull"); + // set BirthName if available + if (eidData.getBirthName() != null) { + log.trace("Find 'BirthName' attribute: " + eidData.getBirthName()); + if (basicConfig + .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_SETBIRTHNAMEIFAVAILABLE, + true)) { + final AlternativeNameType alternativeName = new AlternativeNameType(); + naturalPerson.setAlternativeName(alternativeName); + alternativeName.setFamilyName(eidData.getBirthName()); + log.trace("Adding 'BirthName' to ERnB request ... "); - authProcessData.setForeigner(true); - authProcessData.setIdentityLink(identityLink); - authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, EidasResponseUtils - .parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)) - .getFirst()); + } + } + + return personInfo; + + } - // set bPK and bPKType into auth session - authProcessData.setGenericDataToSession(PvpAttributeDefinitions.BPK_NAME, extendBpkByPrefix(bpk, pendingReq - .getServiceProviderConfiguration().getAreaSpecificTargetIdentifier())); - authProcessData.setGenericDataToSession(PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, + private SzrResultHolder requestSzrForIdentityLink(PersonInfoType personInfo) + throws SzrCommunicationException, EaafException { + //request IdentityLink from SZR + final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(personInfo); + + final Element idlFromSzr = (Element) result.getAssertion(); + IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser(idlFromSzr).parseIdentityLink(); + + // get bPK from SZR + String bpk; + if (basicConfig + .getBasicConfigurationBoolean(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USESRZFORBPKGENERATION, true)) { + bpk = szrClient + .getBpk(personInfo, pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), + basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")) + .get(0); + + } else { + log.debug("Calculating bPK from baseId ... "); + new BpkBuilder(); + final Pair bpkCalc = BpkBuilder + .generateAreaSpecificPersonIdentifier(identityLink.getIdentificationValue(), + identityLink.getIdentificationType(), pendingReq.getServiceProviderConfiguration() .getAreaSpecificTargetIdentifier()); + bpk = bpkCalc.getFirst(); - // store pending-request - requestStoreage.storePendingRequest(pendingReq); - } - } catch (final EidasAttributeException e) { - throw new TaskExecutionException(pendingReq, "Minimum required eIDAS attributeset not found.", e); + } + + return new SzrResultHolder(identityLink, bpk); + + } + + private void checkStateAndWriteRevisionLog(SzrResultHolder idlResult) throws SzrCommunicationException { + // write some infos into revision log + if (idlResult.getIdentityLink() == null) { + log.error("ERnB did not return an identity link."); + throw new SzrCommunicationException("ernb.00", null); - } catch (final EaafException e) { - throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); + } + revisionsLogger.logEvent(pendingReq, + MsConnectorEventCodes.SZR_IDL_RECEIVED, + idlResult.getIdentityLink().getSamlAssertion() + .getAttribute(SimpleIdentityLinkAssertionParser.ASSERTIONID)); - } catch (final Exception e) { - log.error("IdentityLink generation for foreign person FAILED.", e); - throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); + if (idlResult.getBpK() == null) { + log.error("ERnB did not return a bPK for target: " + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); + throw new SzrCommunicationException("ernb.01", null); } + revisionsLogger.logEvent(pendingReq, MsConnectorEventCodes.SZR_BPK_RECEIVED); + log.debug("ERnB communication was successfull"); + } - - private Pair initKeystore(String keyAlias, String keyPw, String path, String type) - throws EaafException, KeyStoreException { - KeyStoreConfiguration keyStoreConfiguration = new KeyStoreConfiguration(); - - final String current = new java.io.File(".").toURI().toString(); - keyStoreConfiguration.setSoftKeyStoreFilePath(current + path); - keyStoreConfiguration.setSoftKeyStorePassword(keyPw); - keyStoreConfiguration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.fromString(type)); - keyStoreConfiguration.setFriendlyName(keyAlias); - keyStoreConfiguration.setKeyStoreName(keyAlias); - return keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); - } - + private String extendBpkByPrefix(String bpk, String type) { String bpkType = null; @@ -406,7 +356,7 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { for (final AttributeDefinition el : attributeMap.keySet()) { - final Class parameterizedType = el.getParameterizedType(); + final Class parameterizedType = el.getParameterizedType(); if (DateTime.class.equals(parameterizedType)) { final DateTime attribute = EidasResponseUtils.translateDateAttribute(el, attributeMap.get(el).asList()); if (attribute != null) { @@ -466,5 +416,72 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { } } + + @Data + private static class SzrResultHolder { + final IIdentityLink identityLink; + final String bpK; + + } + + /** + * Build a dummy IdentityLink and a dummy bPK based on eIDAS information. + * + *

+ * FOR LOCAL TESTING ONLY!!! + * + * @param eidData Information from eIDAS response + * @return IdentityLink and bPK + * @throws ParserConfigurationException In case of an IDL processing error + * @throws SAXException In case of an IDL processing error + * @throws IOException In case of an IDL processing error + * @throws EaafException In case of a bPK generation error + */ + private SzrResultHolder createDummyIdentityLinkForTestDeployment(ErnbEidData eidData) + throws ParserConfigurationException, SAXException, IOException, EaafException { + log.warn("SZR-Dummy IS ACTIVE! IdentityLink is NOT VALID!!!!"); + // create fake IdL + // - fetch IdL template from resources + final InputStream s = CreateIdentityLinkTask.class + .getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); + final Element idlTemplate = DomUtils.parseXmlValidating(s); + + IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); + + // replace data + final Element idlassertion = identityLink.getSamlAssertion(); + + // - set fake baseID; + final Node prIdentification = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + prIdentification.getFirstChild().setNodeValue(eidData.getPseudonym()); + + // - set last name + final Node prFamilyName = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); + prFamilyName.getFirstChild().setNodeValue(eidData.getFamilyName()); + + // - set first name + final Node prGivenName = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); + prGivenName.getFirstChild().setNodeValue(eidData.getGivenName()); + + // - set date of birth + final Node prDateOfBirth = XPathUtils + .selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); + + prDateOfBirth.getFirstChild().setNodeValue(eidData.getFormatedDateOfBirth()); + + identityLink = new SimpleIdentityLinkAssertionParser(idlassertion).parseIdentityLink(); + + new BpkBuilder(); + final Pair bpkCalc = BpkBuilder + .generateAreaSpecificPersonIdentifier(identityLink.getIdentificationValue(), + identityLink.getIdentificationType(), + pendingReq.getServiceProviderConfiguration() + .getAreaSpecificTargetIdentifier()); + return new SzrResultHolder(identityLink, bpkCalc.getFirst()); + + } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml index fbb48229..6cc704ab 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml @@ -58,6 +58,9 @@ + + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index a30ea2a0..2f573f53 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -59,7 +59,7 @@ import szrservices.PersonInfoType; import szrservices.SZRException_Exception; import szrservices.TravelDocumentType; -//@Ignore +@Ignore @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_basic_test.xml") public class SzrClientTestProduction { diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index 888b7631..f67b4d93 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -1,7 +1,5 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME; -import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD; import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; import static org.mockito.ArgumentMatchers.any; import static org.powermock.api.mockito.PowerMockito.when; @@ -9,13 +7,22 @@ import static org.powermock.api.mockito.PowerMockito.when; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.security.KeyStore; +import java.security.Provider; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.apache.commons.lang3.RandomStringUtils; import org.jetbrains.annotations.NotNull; +import org.jose4j.jwa.AlgorithmConstraints; +import org.jose4j.jwa.AlgorithmConstraints.ConstraintType; +import org.jose4j.jws.AlgorithmIdentifiers; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -38,12 +45,18 @@ import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummySpecificCommunicationService; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.JoseUtils; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.JoseUtils.JwsResult; import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; import at.gv.egiz.eaaf.core.api.data.EaafConstants; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreUtils; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; @@ -53,7 +66,6 @@ import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; import eu.eidas.auth.commons.attribute.PersonType; import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; import lombok.val; -import szrservices.PersonInfoType; import szrservices.SZR; import szrservices.SignContentEntry; import szrservices.SignContentResponseType; @@ -66,17 +78,16 @@ import szrservices.SignContentResponseType; @ContextConfiguration("/SpringTest-context_tasks_test.xml") public class CreateIdentityLinkTaskEidNewTest { - @Autowired(required = true) private CreateIdentityLinkTask task; - // @Autowired(required = true) - // private FinalizeAuthenticationTask authTask; - @Autowired(required = true) - private DummySpecificCommunicationService commService; + @Autowired(required = true) private IConfiguration basicConfig; @Autowired protected EidasAttributeRegistry attrRegistry; + + @Autowired + EaafKeyStoreFactory keyStoreFactory; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -88,6 +99,13 @@ public class CreateIdentityLinkTaskEidNewTest { private static final String PW = "f/+saJBc3a}*/T^s"; private static final String ALIAS = "connectorkeypair"; + private static final List BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING = Collections.unmodifiableList( + Arrays.asList( + AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256, + AlgorithmIdentifiers.ECDSA_USING_P521_CURVE_AND_SHA512, + AlgorithmIdentifiers.RSA_PSS_USING_SHA256, + AlgorithmIdentifiers.RSA_PSS_USING_SHA512)); + @Rule public final SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -99,7 +117,8 @@ public class CreateIdentityLinkTaskEidNewTest { @BeforeClass public static void classInitializer() throws IOException { final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_3.properties"); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/junit_config_3.properties"); } @@ -118,16 +137,13 @@ public class CreateIdentityLinkTaskEidNewTest { spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); spConfig.put(PROP_CONFIG_SP_NEW_EID_MODE, "true"); - spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_KEYSTORE_PASSWORD, PW); - spConfig.put(PROP_CONFIG_SP_AUTHBLOCK_KEYSTSTORE_FRIENDLYNAME, ALIAS); oaParam = new DummySpConfiguration(spConfig, basicConfig); pendingReq = new TestRequestImpl(); - AuthenticationResponse response = buildDummyAuthResponse(); - + final AuthenticationResponse response = buildDummyAuthResponse(); pendingReq.getSessionData(AuthProcessDataWrapper.class) - .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); pendingReq.setSpConfig(oaParam); pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); pendingReq.setAuthUrl("http://test.com/"); @@ -141,73 +157,109 @@ public class CreateIdentityLinkTaskEidNewTest { @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { - AttributeDefinition attributeDef = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER) - .nameUri(new URI("ad", "sd", "ff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "af")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") - .build(); - AttributeDefinition attributeDef2 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME) - .nameUri(new URI("ad", "sd", "fff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "aff")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") - .build(); - AttributeDefinition attributeDef3 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME) - .nameUri(new URI("ad", "sd", "ffff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "afff")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") - .build(); - AttributeDefinition attributeDef4 = AttributeDefinition.builder().friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH) - .nameUri(new URI("ad", "sd", "fffff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "affff")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller") - .build(); - - ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder().put(attributeDef, "de/st/" + RandomStringUtils - .randomNumeric(64)).put(attributeDef2, RandomStringUtils.randomAlphabetic(10)).put(attributeDef3, - RandomStringUtils - .randomAlphabetic(10)) - .put(attributeDef4, "2001-01-01").build(); - + final AttributeDefinition attributeDef = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER) + .nameUri(new URI("ad", "sd", "ff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "af")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") + .build(); + final AttributeDefinition attributeDef2 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME) + .nameUri(new URI("ad", "sd", "fff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "aff")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") + .build(); + final AttributeDefinition attributeDef3 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME) + .nameUri(new URI("ad", "sd", "ffff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "afff")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") + .build(); + final AttributeDefinition attributeDef4 = AttributeDefinition.builder().friendlyName( + Constants.eIDAS_ATTR_DATEOFBIRTH) + .nameUri(new URI("ad", "sd", "fffff")) + .personType(PersonType.LEGAL_PERSON) + .xmlType(new QName("http://saf", "as", "affff")) + .attributeValueMarshaller( + "eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller") + .build(); + + final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder().put(attributeDef, "de/st/" + + RandomStringUtils + .randomNumeric(64)).put(attributeDef2, RandomStringUtils.randomAlphabetic(10)).put(attributeDef3, + RandomStringUtils + .randomAlphabetic(10)) + .put(attributeDef4, "2001-01-01").build(); val b = new AuthenticationResponse.Builder(); - return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf") - .attributes(attributeMap).build(); + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf") + .subjectNameIdFormat("afaf") + .attributes(attributeMap).build(); } @Test - public void fullTest() { - // keystore password f/+saJBc3a}*/T^s - try { - - String test = szrMock.getStammzahlEncrypted(new PersonInfoType(), false); - - when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); - val signContentResp = new SignContentResponseType(); - SignContentEntry signContentEntry = new SignContentEntry(); - signContentEntry.setValue(RandomStringUtils.randomAlphanumeric(10)); - signContentResp.getOut().add(signContentEntry); - when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); - task.execute(pendingReq, executionContext); - - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - + public void successfulProcess() throws Exception { + //initialize test + when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); + val signContentResp = new SignContentResponseType(); + final SignContentEntry signContentEntry = new SignContentEntry(); + signContentEntry.setValue(RandomStringUtils.randomAlphanumeric(10)); + signContentResp.getOut().add(signContentEntry); + when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); + + //perform test + task.execute(pendingReq, executionContext); + + //validate state + final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + Assert.assertNotNull("AuthProcessData", authProcessData); + Assert.assertNotNull("eidasBind", authProcessData.getGenericDataFromSession(Constants.EIDAS_BIND, String.class)); + + String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class); + Assert.assertNotNull("AuthBlock", authBlock); + + //check authblock signature + final AlgorithmConstraints constraints = new AlgorithmConstraints(ConstraintType.PERMIT, + BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING + .toArray(new String[BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.size()])); + Pair keyStore = getKeyStore(); + X509Certificate[] trustedCerts = EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore.getFirst(), ALIAS, PW.toCharArray(), true, "junit").getSecond(); + JwsResult result = JoseUtils.validateSignature(authBlock, Arrays.asList(trustedCerts) , constraints); + Assert.assertTrue("AuthBlock not valid", result.isValid()); + + } + private Pair getKeyStore() throws EaafException { + // read Connector wide config data TODO connector wide! + String keyStoreName = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_NAME); + String keyStorePw = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PASSWORD); + String keyStorePath = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PATH); + String keyStoreType = basicConfig + .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_TYPE); + + + //build new KeyStore configuration + KeyStoreConfiguration keyStoreConfiguration = new KeyStoreConfiguration(); + keyStoreConfiguration.setFriendlyName("jUnit test"); + + keyStoreConfiguration.setSoftKeyStoreFilePath(keyStorePath); + keyStoreConfiguration.setSoftKeyStorePassword(keyStorePw); + keyStoreConfiguration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.fromString(keyStoreType)); + keyStoreConfiguration.setKeyStoreName(keyStoreName); + + //build new KeyStore based on configuration + return keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); + } } - - diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test.xml index dd116bd3..7d5a4c53 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test.xml +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_tasks_test.xml @@ -45,6 +45,9 @@ ref="specificConnectorAdditionalAttributesFileWithPath" /> + + 0.3 0.4 - 1.1.8 + 1.1.10-SNAPSHOT 5.2.9.RELEASE 3.0.11.RELEASE 3.4.0 -- cgit v1.2.3 From eb1ca70419a2e1863c6cafd5d57efed74061a9f9 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 9 Nov 2020 09:23:51 +0100 Subject: fix some more problems with jUnit tests --- basicConfig/default_config.properties | 2 ++ connector/src/test/resources/config/junit_config_1.properties | 9 +++++---- connector/src/test/resources/config/junit_config_3.properties | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/basicConfig/default_config.properties b/basicConfig/default_config.properties index 2e0aebcc..483e9c97 100644 --- a/basicConfig/default_config.properties +++ b/basicConfig/default_config.properties @@ -39,6 +39,7 @@ eidas.ms.auth.eIDAS.node_v2.loa.requested.minimum=http://eidas.europa.eu/LoA/hig eidas.ms.auth.eIDAS.szrclient.useTestService=true eidas.ms.auth.eIDAS.szrclient.endpoint.prod= eidas.ms.auth.eIDAS.szrclient.endpoint.test=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.szrclient.ssl.keyStore.type=pkcs12 eidas.ms.auth.eIDAS.szrclient.ssl.keyStore.path=keys/..... eidas.ms.auth.eIDAS.szrclient.ssl.keyStore.password= eidas.ms.auth.eIDAS.szrclient.ssl.trustStore.path= @@ -89,6 +90,7 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true ## PVP2 S-Profile end-point configuration +eidas.ms.pvp2.keystore.type=jks eidas.ms.pvp2.keystore.path=keys/..... eidas.ms.pvp2.keystore.password= eidas.ms.pvp2.key.metadata.alias= diff --git a/connector/src/test/resources/config/junit_config_1.properties b/connector/src/test/resources/config/junit_config_1.properties index 8bff74a9..f498cac4 100644 --- a/connector/src/test/resources/config/junit_config_1.properties +++ b/connector/src/test/resources/config/junit_config_1.properties @@ -80,12 +80,13 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true ## PVP2 S-Profile end-point configuration +eidas.ms.pvp2.keystore.type=jks eidas.ms.pvp2.keystore.path=keys/junit.jks eidas.ms.pvp2.keystore.password=password -eidas.ms.pvp2.key.metadata.alias= -eidas.ms.pvp2.key.metadata.password= -eidas.ms.pvp2.key.signing.alias= -eidas.ms.pvp2.key.signing.password= +eidas.ms.pvp2.key.metadata.alias=meta +eidas.ms.pvp2.key.metadata.password=password +eidas.ms.pvp2.key.signing.alias=sig +eidas.ms.pvp2.key.signing.password=password eidas.ms.pvp2.metadata.validity=24 eidas.ms.pvp2.metadata.organisation.name=JUnit diff --git a/connector/src/test/resources/config/junit_config_3.properties b/connector/src/test/resources/config/junit_config_3.properties index 2abda7db..1199fdf5 100644 --- a/connector/src/test/resources/config/junit_config_3.properties +++ b/connector/src/test/resources/config/junit_config_3.properties @@ -80,6 +80,7 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true ## PVP2 S-Profile end-point configuration +eidas.ms.pvp2.keystore.type=jks eidas.ms.pvp2.keystore.path=keys/junit.jks eidas.ms.pvp2.keystore.password=password eidas.ms.pvp2.key.metadata.alias= -- cgit v1.2.3 From 7bbd7935548ee50fd5c70caf5503de1b7a2b025d Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 9 Nov 2020 10:00:25 +0100 Subject: switch to next release version of EAAF components to use already defined attribute-name for signed AuthBlock --- .../specific/connector/attributes/AuthBlockAttributeBuilder.java | 9 +++++---- pom.xml | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java index 80f91e57..be9f8862 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/attributes/AuthBlockAttributeBuilder.java @@ -19,6 +19,11 @@ package at.asitplus.eidas.specific.connector.attributes; +import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME; +import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_AUTHBLOCK_SIGNED_NAME; + +import org.apache.commons.lang3.StringUtils; + import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; import at.gv.egiz.eaaf.core.api.idp.IAuthData; @@ -27,15 +32,11 @@ import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; -import org.apache.commons.lang3.StringUtils; @PvpMetadata public class AuthBlockAttributeBuilder implements IPvpAttributeBuilder { - public static final String EID_AUTHBLOCK_SIGNED_NAME = "urn:eidgvat:attributes.authblock.signed"; - public static final String EID_AUTHBLOCK_SIGNED_FRIENDLY_NAME = "userAuthBlock"; - @Override public String getName() { return EID_AUTHBLOCK_SIGNED_NAME; diff --git a/pom.xml b/pom.xml index dad571d3..5d847e9a 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ 0.3 0.4 - 1.1.10-SNAPSHOT + 1.1.9 5.2.9.RELEASE 3.0.11.RELEASE 3.4.0 -- cgit v1.2.3 From 23ff9db88aa5d6065546dcfe8593822997597137 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 9 Nov 2020 10:52:43 +0100 Subject: fix broken code --- .../attributes/AuthBlockAttributeBuilderTest.java | 26 +++++++++++----------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java index 50376e08..b7c6cd44 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java @@ -1,12 +1,7 @@ package at.asitplus.eidas.specific.connector.test.attributes; -import at.asitplus.eidas.specific.connector.attributes.AuthBlockAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; -import at.gv.egiz.eaaf.core.impl.idp.auth.attributes.AbstractAttributeBuilderTest; -import lombok.extern.slf4j.Slf4j; +import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_AUTHBLOCK_SIGNED_NAME; + import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -16,9 +11,14 @@ import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static at.asitplus.eidas.specific.connector.attributes.AuthBlockAttributeBuilder.EID_AUTHBLOCK_SIGNED_NAME; -import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.SZR_AUTHBLOCK; +import at.asitplus.eidas.specific.connector.attributes.AuthBlockAttributeBuilder; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; +import at.gv.egiz.eaaf.core.impl.idp.auth.attributes.AbstractAttributeBuilderTest; +import lombok.extern.slf4j.Slf4j; @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @@ -46,7 +46,7 @@ public class AuthBlockAttributeBuilderTest extends AbstractAttributeBuilderTest log.info("starting: " + mTestName); try { final IAuthData authData = buildAuthData(); - ((AuthenticationData) authData).setGenericData(SZR_AUTHBLOCK, JSW); + ((AuthenticationData) authData).setGenericData(Constants.SZR_AUTHBLOCK, JSW); final String value = attrBuilde.build(spConfig, authData, gen); @@ -63,7 +63,7 @@ public class AuthBlockAttributeBuilderTest extends AbstractAttributeBuilderTest log.info("starting: " + mTestName); try { final IAuthData authData = buildAuthData(); - ((AuthenticationData) authData).setGenericData(SZR_AUTHBLOCK, null); + ((AuthenticationData) authData).setGenericData(Constants.SZR_AUTHBLOCK, null); final String value = attrBuilde.build(spConfig, authData, gen); Assert.fail("Attr. Builder provide no 'UnavailableAttributeException'"); @@ -82,7 +82,7 @@ public class AuthBlockAttributeBuilderTest extends AbstractAttributeBuilderTest log.info("starting: " + mTestName); try { final IAuthData authData = buildAuthData(); - ((AuthenticationData) authData).setGenericData(SZR_AUTHBLOCK, ""); + ((AuthenticationData) authData).setGenericData(Constants.SZR_AUTHBLOCK, ""); final String value = attrBuilde.build(spConfig, authData, gen); Assert.fail("Attr. Builder provide no 'UnavailableAttributeException'"); -- cgit v1.2.3 From b04c31afa0213048367ee6e4eec4fb52dfd59915 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 11 Nov 2020 11:35:27 +0100 Subject: verify on start-up, if AuthBlock signing-key is accessable --- .../modules/auth/eidas/v2/service/AuthBlockSigningService.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java index 30d255b9..cb96b0a0 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java @@ -124,6 +124,10 @@ public class AuthBlockSigningService { //build new KeyStore based on configuration keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); + //check if Key is accessable + EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore.getFirst(), getKeyAlias(), getKeyPassword(), true, KEYSTORE_FRIENDLYNAME); + log.info("AuthBlock signing-service successful initialized"); } -- cgit v1.2.3 From 65baff23786c76746f4b188d3e6e59fd112e3030 Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 13 Nov 2020 08:39:00 +0100 Subject: improved Junit tests --- .../builder/AuthenticationDataBuilder.java | 13 +- .../test/AuthenticationDataBuilderTest.java | 32 ++-- .../resources/config/junit_config_3.properties | 2 +- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 204 ++++++++++++--------- 4 files changed, 148 insertions(+), 103 deletions(-) diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java index ef1a1f2b..13cceafb 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java @@ -57,7 +57,7 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder AuthenticationData authData = new AuthenticationData(); boolean isEidModeNew = pendingReq.getServiceProviderConfiguration() - .isConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE, false); + .isConfigurationValue(MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE, false); if (isEidModeNew) { authData = (AuthenticationData) super.buildAuthenticationData(pendingReq); @@ -66,11 +66,11 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder generateDeprecatedBasicAuthData(authData, pendingReq, authProcessData); // set specific informations - authData.setSsoSessionValidTo(new Date(new Date().getTime() - + MsEidasNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); + authData.setSsoSessionValidTo( + new Date(new Date().getTime() + MsEidasNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); - } catch (EaafBuilderException | EaafParserException | EaafConfigurationException - | XPathException | DOMException e) { + } catch (EaafBuilderException | EaafParserException + | EaafConfigurationException | XPathException | DOMException e) { log.warn("Can not build authentication data from auth. process information"); throw new EaafAuthenticationException("builder.11", new Object[]{e.getMessage()}, e); @@ -108,8 +108,7 @@ public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder @Override protected Pair getEncryptedBpkFromPvpAttribute(IAuthProcessDataContainer arg0, - AuthenticationData arg1, - ISpConfiguration arg2) throws EaafBuilderException { + AuthenticationData arg1, ISpConfiguration arg2) throws EaafBuilderException { return null; } diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java index 78d2ee1a..1721fe61 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java @@ -4,6 +4,7 @@ package at.asitplus.eidas.specific.connector.test; import at.asitplus.eidas.specific.connector.builder.AuthenticationDataBuilder; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; @@ -13,6 +14,7 @@ import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; import net.shibboleth.utilities.java.support.component.ComponentInitializationException; import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -34,12 +36,7 @@ import java.util.Map; import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({"/applicationContext.xml", - "/SpringTest_connector.beans.xml", - "/eaaf_core.beans.xml", - "/eaaf_pvp.beans.xml", - "/eaaf_pvp_idp.beans.xml", - "/spring/SpringTest-context_simple_storage.xml" }) +@ContextConfiguration({"/applicationContext.xml", "/SpringTest_connector.beans.xml", "/eaaf_core.beans.xml", "/eaaf_pvp.beans.xml", "/eaaf_pvp_idp.beans.xml", "/spring/SpringTest-context_simple_storage.xml"}) @WebAppConfiguration public class AuthenticationDataBuilderTest { @@ -55,6 +52,9 @@ public class AuthenticationDataBuilderTest { private DummySpConfiguration oaParam; + private String eidasBind; + private String authBlock; + @BeforeClass public static void classInitializer() throws InitializationException, ComponentInitializationException { @@ -82,16 +82,26 @@ public class AuthenticationDataBuilderTest { pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); pendingReq.setSpConfig(oaParam); pendingReq.getSessionData(AuthProcessDataWrapper.class).setEidProcess(true); - pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.SZR_AUTHBLOCK, RandomStringUtils.randomAlphanumeric(20)); - pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.EIDAS_BIND, RandomStringUtils.randomAlphanumeric(20)); - - + authBlock = RandomStringUtils.randomAlphanumeric(20); + eidasBind = RandomStringUtils.randomAlphanumeric(20); + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.SZR_AUTHBLOCK, authBlock); + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.EIDAS_BIND, eidasBind); LocaleContextHolder.resetLocaleContext(); } @Test public void first() throws EaafAuthenticationException { - authenticationDataBuilder.buildAuthenticationData(pendingReq); + IAuthData authData = authenticationDataBuilder.buildAuthenticationData(pendingReq); + + Assert.assertNotNull("AuthData null", authData); + Assert.assertNotNull("authBlock null", authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class)); + Assert.assertNotNull("eidasBind null", authData.getGenericData(Constants.EIDAS_BIND, String.class)); + Assert.assertNotNull("eidasBind null", authData.getEidasQaaLevel()); + String authBlock = authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class); + String eidasBind = authData.getGenericData(Constants.EIDAS_BIND, String.class); + + Assert.assertEquals("authBlock not equal", authBlock, this.authBlock); + Assert.assertEquals("eidasBind not equal", eidasBind, this.eidasBind); } } diff --git a/connector/src/test/resources/config/junit_config_3.properties b/connector/src/test/resources/config/junit_config_3.properties index 1199fdf5..32e30790 100644 --- a/connector/src/test/resources/config/junit_config_3.properties +++ b/connector/src/test/resources/config/junit_config_3.properties @@ -100,7 +100,7 @@ eidas.ms.pvp2.metadata.contact.email=max@junit.test eidas.ms.sp.0.uniqueID= eidas.ms.sp.0.pvp2.metadata.truststore=keys/junit.jks eidas.ms.sp.0.pvp2.metadata.truststore.password=password -eidas.ms.sp.0.eidMode=new +eidas.ms.sp.0.newEidMode=true #eidas.ms.sp.0.friendlyName= #eidas.ms.sp.0.pvp2.metadata.url= diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index f67b4d93..d08855f2 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -2,6 +2,9 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doThrow; import static org.powermock.api.mockito.PowerMockito.when; import java.io.IOException; @@ -18,14 +21,19 @@ import java.util.Map; import javax.xml.namespace.QName; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicationException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.AuthBlockSigningService; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import org.apache.commons.lang3.RandomStringUtils; import org.jetbrains.annotations.NotNull; import org.jose4j.jwa.AlgorithmConstraints; import org.jose4j.jwa.AlgorithmConstraints.ConstraintType; import org.jose4j.jws.AlgorithmIdentifiers; +import org.jose4j.lang.JoseException; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -67,6 +75,7 @@ import eu.eidas.auth.commons.attribute.PersonType; import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; import lombok.val; import szrservices.SZR; +import szrservices.SZRException_Exception; import szrservices.SignContentEntry; import szrservices.SignContentResponseType; @@ -85,10 +94,13 @@ public class CreateIdentityLinkTaskEidNewTest { private IConfiguration basicConfig; @Autowired protected EidasAttributeRegistry attrRegistry; - + @Autowired EaafKeyStoreFactory keyStoreFactory; + @Autowired + private AuthBlockSigningService authBlockSigner; + final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; private MockHttpServletResponse httpResp; @@ -99,13 +111,11 @@ public class CreateIdentityLinkTaskEidNewTest { private static final String PW = "f/+saJBc3a}*/T^s"; private static final String ALIAS = "connectorkeypair"; - private static final List BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING = Collections.unmodifiableList( - Arrays.asList( - AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256, - AlgorithmIdentifiers.ECDSA_USING_P521_CURVE_AND_SHA512, - AlgorithmIdentifiers.RSA_PSS_USING_SHA256, + private static final List BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING = Collections.unmodifiableList(Arrays + .asList(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256, + AlgorithmIdentifiers.ECDSA_USING_P521_CURVE_AND_SHA512, AlgorithmIdentifiers.RSA_PSS_USING_SHA256, AlgorithmIdentifiers.RSA_PSS_USING_SHA512)); - + @Rule public final SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -117,8 +127,7 @@ public class CreateIdentityLinkTaskEidNewTest { @BeforeClass public static void classInitializer() throws IOException { final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current - + "src/test/resources/config/junit_config_3.properties"); + System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_3.properties"); } @@ -155,54 +164,6 @@ public class CreateIdentityLinkTaskEidNewTest { szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); } - @NotNull - private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { - final AttributeDefinition attributeDef = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER) - .nameUri(new URI("ad", "sd", "ff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "af")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") - .build(); - final AttributeDefinition attributeDef2 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME) - .nameUri(new URI("ad", "sd", "fff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "aff")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") - .build(); - final AttributeDefinition attributeDef3 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME) - .nameUri(new URI("ad", "sd", "ffff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "afff")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller") - .build(); - final AttributeDefinition attributeDef4 = AttributeDefinition.builder().friendlyName( - Constants.eIDAS_ATTR_DATEOFBIRTH) - .nameUri(new URI("ad", "sd", "fffff")) - .personType(PersonType.LEGAL_PERSON) - .xmlType(new QName("http://saf", "as", "affff")) - .attributeValueMarshaller( - "eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller") - .build(); - - final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder().put(attributeDef, "de/st/" - + RandomStringUtils - .randomNumeric(64)).put(attributeDef2, RandomStringUtils.randomAlphabetic(10)).put(attributeDef3, - RandomStringUtils - .randomAlphabetic(10)) - .put(attributeDef4, "2001-01-01").build(); - - val b = new AuthenticationResponse.Builder(); - return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf") - .subjectNameIdFormat("afaf") - .attributes(attributeMap).build(); - } - @Test public void successfulProcess() throws Exception { //initialize test @@ -212,54 +173,129 @@ public class CreateIdentityLinkTaskEidNewTest { signContentEntry.setValue(RandomStringUtils.randomAlphanumeric(10)); signContentResp.getOut().add(signContentEntry); when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); - + //perform test task.execute(pendingReq, executionContext); - + //validate state final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); Assert.assertNotNull("AuthProcessData", authProcessData); Assert.assertNotNull("eidasBind", authProcessData.getGenericDataFromSession(Constants.EIDAS_BIND, String.class)); - + String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class); Assert.assertNotNull("AuthBlock", authBlock); - + //check authblock signature final AlgorithmConstraints constraints = new AlgorithmConstraints(ConstraintType.PERMIT, - BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING - .toArray(new String[BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.size()])); - Pair keyStore = getKeyStore(); - X509Certificate[] trustedCerts = EaafKeyStoreUtils.getPrivateKeyAndCertificates( - keyStore.getFirst(), ALIAS, PW.toCharArray(), true, "junit").getSecond(); - JwsResult result = JoseUtils.validateSignature(authBlock, Arrays.asList(trustedCerts) , constraints); + BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.toArray(new String[BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.size()])); + Pair keyStore = getKeyStore(); + X509Certificate[] trustedCerts = EaafKeyStoreUtils + .getPrivateKeyAndCertificates(keyStore.getFirst(), ALIAS, PW.toCharArray(), true, "junit").getSecond(); + JwsResult result = JoseUtils.validateSignature(authBlock, Arrays.asList(trustedCerts), constraints); Assert.assertTrue("AuthBlock not valid", result.isValid()); - + + } + + @Test + public void getStammzahlEncryptedExceptionTest() throws Exception { + try { + when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(null); + task.execute(pendingReq, executionContext); + } catch (TaskExecutionException e) { + Assert.assertEquals("Incorrect exception thrown", e.getMessage(), + "IdentityLink generation for foreign person " + "FAILED."); + Assert.assertEquals("Incorrect exception thrown", ((SzrCommunicationException) e.getCause()).getErrorId(), + "ernb.01"); + Assert.assertTrue("Incorrect exception thrown", e.getCause().getMessage().contains("Stammzahl response empty")); + } + } + + @Test + public void signContentExceptionTest() throws Exception { + try { + when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); + when(szrMock, "signContent", any(), any(), any()).thenReturn(null); + task.execute(pendingReq, executionContext); + } catch (TaskExecutionException e) { + Assert.assertEquals("Incorrect exception thrown", e.getMessage(), + "IdentityLink generation for foreign person " + "FAILED."); + Assert.assertEquals("Incorrect exception thrown", ((SzrCommunicationException) e.getCause()).getErrorId(), + "ernb.01"); + Assert.assertTrue("Incorrect exception thrown", e.getCause().getMessage().contains("BcBind response empty")); + } + } + + @Ignore + @Test + public void exceptionTest() throws Exception { + try { + when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); + val signContentResp = new SignContentResponseType(); + final SignContentEntry signContentEntry = new SignContentEntry(); + signContentEntry.setValue(RandomStringUtils.randomAlphanumeric(10)); + signContentResp.getOut().add(signContentEntry); + when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); + doThrow(new EaafException("test")).when(authBlockSigner) + .buildSignedAuthBlock(pendingReq.getUniqueTransactionIdentifier()); + + task.execute(pendingReq, executionContext); + } catch (TaskExecutionException e) { + Assert.assertEquals("Incorrect exception thrown", e.getMessage(), + "IdentityLink generation for foreign person " + "FAILED."); + Assert.assertTrue("Incorrect exception thrown", e.getCause() instanceof EaafException); + Assert.assertTrue("Incorrect exception thrown", e.getCause().getMessage().contains("test")); + } + } private Pair getKeyStore() throws EaafException { - // read Connector wide config data TODO connector wide! - String keyStoreName = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_NAME); - String keyStorePw = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PASSWORD); - String keyStorePath = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PATH); - String keyStoreType = basicConfig - .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_TYPE); - - + // read Connector wide config data TODO connector wide! + String keyStoreName = basicConfig.getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_NAME); + String keyStorePw = basicConfig.getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PASSWORD); + String keyStorePath = basicConfig.getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_PATH); + String keyStoreType = basicConfig.getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_TYPE); + + //build new KeyStore configuration KeyStoreConfiguration keyStoreConfiguration = new KeyStoreConfiguration(); keyStoreConfiguration.setFriendlyName("jUnit test"); - + keyStoreConfiguration.setSoftKeyStoreFilePath(keyStorePath); keyStoreConfiguration.setSoftKeyStorePassword(keyStorePw); - keyStoreConfiguration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.fromString(keyStoreType)); + keyStoreConfiguration.setKeyStoreType(KeyStoreConfiguration.KeyStoreType.fromString(keyStoreType)); keyStoreConfiguration.setKeyStoreName(keyStoreName); - + //build new KeyStore based on configuration - return keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); - + return keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); + } + @NotNull + private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { + final AttributeDefinition attributeDef = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef2 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME).nameUri(new URI("ad", "sd", "fff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "aff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef3 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME).nameUri(new URI("ad", "sd", "ffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef4 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH).nameUri(new URI("ad", "sd", "fffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); + + final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder() + .put(attributeDef, "de/st/" + RandomStringUtils.randomNumeric(64)) + .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) + .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)).put(attributeDef4, "2001-01-01").build(); + + val b = new AuthenticationResponse.Builder(); + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf") + .attributes(attributeMap).build(); + } } -- cgit v1.2.3 From 3d01b42c1e57145850feefd49327cec2bc8b7843 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 24 Nov 2020 12:05:00 +0100 Subject: remove unused code --- .../specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java | 2 +- .../specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java index cb96b0a0..ccc6eb0c 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java @@ -124,7 +124,7 @@ public class AuthBlockSigningService { //build new KeyStore based on configuration keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfiguration); - //check if Key is accessable + //check if Key is accessible EaafKeyStoreUtils.getPrivateKeyAndCertificates( keyStore.getFirst(), getKeyAlias(), getKeyPassword(), true, KEYSTORE_FRIENDLYNAME); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index 1ffd56e4..80142b09 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -474,7 +474,6 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { identityLink = new SimpleIdentityLinkAssertionParser(idlassertion).parseIdentityLink(); - new BpkBuilder(); final Pair bpkCalc = BpkBuilder .generateAreaSpecificPersonIdentifier(identityLink.getIdentificationValue(), identityLink.getIdentificationType(), -- cgit v1.2.3 From d01abea064f33d1c985464aadf3e2326c6ba3219 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 27 Nov 2020 09:07:27 +0100 Subject: upatate AuthBlock format in case of E-ID like authentication --- eidas_modules/authmodule-eIDAS-v2/pom.xml | 6 ++- .../eidas/v2/service/AuthBlockSigningService.java | 52 ++++++++++++++++++++-- .../eidas/v2/tasks/CreateIdentityLinkTask.java | 2 +- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 37 ++------------- pom.xml | 9 +++- 5 files changed, 65 insertions(+), 41 deletions(-) diff --git a/eidas_modules/authmodule-eIDAS-v2/pom.xml b/eidas_modules/authmodule-eIDAS-v2/pom.xml index 4fe2bb36..b2e841fb 100644 --- a/eidas_modules/authmodule-eIDAS-v2/pom.xml +++ b/eidas_modules/authmodule-eIDAS-v2/pom.xml @@ -123,8 +123,10 @@ org.apache.cxf cxf-rt-transports-http - + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + javax.servlet diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java index ccc6eb0c..ad9b1082 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java @@ -1,11 +1,15 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.service; +import java.io.Serializable; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Provider; import java.security.cert.X509Certificate; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; import java.util.Base64; +import java.util.UUID; import javax.annotation.PostConstruct; @@ -14,11 +18,18 @@ import org.jose4j.lang.JoseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.JoseUtils; +import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.exception.EaafKeyAccessException; import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; @@ -27,6 +38,7 @@ import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreUtils; import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; import at.gv.egiz.eaaf.core.impl.data.Pair; +import lombok.Data; import lombok.extern.slf4j.Slf4j; /** @@ -55,18 +67,22 @@ public class AuthBlockSigningService { /** * Build and sign an AuthBlock for E-ID system. * - * @param dataToSign data that should be added into AuthBlock + * @param pendingReq data that should be added into AuthBlock * @return serialized JWS * @throws JsonProcessingException In case of a AuthBlock generation error * @throws JoseException In case of a JWS signing error * @throws EaafException In case of a KeyStore or Key error */ - public String buildSignedAuthBlock(String dataToSign) + public String buildSignedAuthBlock(IRequest pendingReq) throws JsonProcessingException, EaafException, JoseException { - log.debug("Building and sign authBlock with data: {}", dataToSign); // build AuthBlock - String jwsPayload = mapper.writeValueAsString(dataToSign); + EidasAuchBlock authBlock = new EidasAuchBlock(); + authBlock.setChallenge(UUID.randomUUID().toString()); + authBlock.setTimestamp(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)); + authBlock.setUniqueId(pendingReq.getRawData(MsEidasNodeConstants.DATA_REQUESTERID, String.class)); + String jwsPayload = mapper.writeValueAsString(authBlock); + log.debug("Building and sign authBlock with data: {}", jwsPayload); //sign JWS return JoseUtils @@ -148,4 +164,32 @@ public class AuthBlockSigningService { .getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEY_ALIAS); } + + /** + * Technical AuthBlock for eIDAS Authentication. + * + * @author tlenz + * + */ + @Data + public class EidasAuchBlock implements Serializable { + + private static final long serialVersionUID = -2013435642666124497L; + + @JsonProperty("challenge") + private String challenge; + + @JsonProperty("timestamp") + @JsonSerialize(using = LocalDateTimeSerializer.class) + @JsonDeserialize(using = LocalDateTimeDeserializer.class) + @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + private LocalDateTime timestamp; + + @JsonProperty("appId") + private String uniqueId; + + + } + + } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java index 80142b09..f9142f8e 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/CreateIdentityLinkTask.java @@ -157,7 +157,7 @@ public class CreateIdentityLinkTask extends AbstractAuthServletTask { EID_STATUS); //get signed AuthBlock - String jwsSignature = authBlockSigner.buildSignedAuthBlock(pendingReq.getUniqueTransactionIdentifier()); + String jwsSignature = authBlockSigner.buildSignedAuthBlock(pendingReq); //inject personal-data into session authProcessData.setGenericDataToSession(Constants.SZR_AUTHBLOCK, jwsSignature); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java index d08855f2..dd485ee6 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java @@ -2,9 +2,6 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.doThrow; import static org.powermock.api.mockito.PowerMockito.when; import java.io.IOException; @@ -21,19 +18,14 @@ import java.util.Map; import javax.xml.namespace.QName; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicationException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.AuthBlockSigningService; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import org.apache.commons.lang3.RandomStringUtils; import org.jetbrains.annotations.NotNull; import org.jose4j.jwa.AlgorithmConstraints; import org.jose4j.jwa.AlgorithmConstraints.ConstraintType; import org.jose4j.jws.AlgorithmIdentifiers; -import org.jose4j.lang.JoseException; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -51,6 +43,8 @@ import com.skjolberg.mockito.soap.SoapServiceRule; import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicationException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.AuthBlockSigningService; import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.JoseUtils; @@ -61,6 +55,7 @@ import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreUtils; import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; @@ -75,7 +70,6 @@ import eu.eidas.auth.commons.attribute.PersonType; import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; import lombok.val; import szrservices.SZR; -import szrservices.SZRException_Exception; import szrservices.SignContentEntry; import szrservices.SignContentResponseType; @@ -193,7 +187,7 @@ public class CreateIdentityLinkTaskEidNewTest { .getPrivateKeyAndCertificates(keyStore.getFirst(), ALIAS, PW.toCharArray(), true, "junit").getSecond(); JwsResult result = JoseUtils.validateSignature(authBlock, Arrays.asList(trustedCerts), constraints); Assert.assertTrue("AuthBlock not valid", result.isValid()); - + } @Test @@ -225,29 +219,6 @@ public class CreateIdentityLinkTaskEidNewTest { } } - @Ignore - @Test - public void exceptionTest() throws Exception { - try { - when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); - val signContentResp = new SignContentResponseType(); - final SignContentEntry signContentEntry = new SignContentEntry(); - signContentEntry.setValue(RandomStringUtils.randomAlphanumeric(10)); - signContentResp.getOut().add(signContentEntry); - when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); - doThrow(new EaafException("test")).when(authBlockSigner) - .buildSignedAuthBlock(pendingReq.getUniqueTransactionIdentifier()); - - task.execute(pendingReq, executionContext); - } catch (TaskExecutionException e) { - Assert.assertEquals("Incorrect exception thrown", e.getMessage(), - "IdentityLink generation for foreign person " + "FAILED."); - Assert.assertTrue("Incorrect exception thrown", e.getCause() instanceof EaafException); - Assert.assertTrue("Incorrect exception thrown", e.getCause().getMessage().contains("test")); - } - - } - private Pair getKeyStore() throws EaafException { // read Connector wide config data TODO connector wide! String keyStoreName = basicConfig.getBasicConfiguration(MsEidasNodeConstants.PROP_CONFIG_AUTHBLOCK_KEYSTORE_NAME); diff --git a/pom.xml b/pom.xml index 5d847e9a..2c14ea4a 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ 0.3 0.4 - 1.1.9 + 1.1.10-SNAPSHOT 5.2.9.RELEASE 3.0.11.RELEASE 3.4.0 @@ -30,6 +30,8 @@ 29.0-jre 2.10.6 1.7.30 + 2.11.3 + 4.13 @@ -202,6 +204,11 @@ commons-collections4 ${commons-collections4.version} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-datatype-jsr310.version} + -- cgit v1.2.3 From 7a62a84f23b3a1a1027ebda31fb790ee072793cc Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 27 Nov 2020 09:08:10 +0100 Subject: read unique transactionId from AuthnRequest to reuse it for eIDAS authentication --- .../verification/AuthnRequestValidator.java | 247 +++++++++++++-------- .../connector/test/AuthnRequestValidatorTest.java | 52 ++++- .../resources/config/junit_config_1.properties | 2 +- connector/src/test/resources/data/pvp2_authn_2.xml | 4 + connector/src/test/resources/data/pvp2_authn_3.xml | 3 + 5 files changed, 205 insertions(+), 103 deletions(-) diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java index 26176c49..a9eb06be 100644 --- a/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java @@ -46,11 +46,13 @@ import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.connector.config.ServiceProviderConfiguration; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; import at.gv.egiz.eaaf.core.api.data.PvpAttributeDefinitions; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; 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.api.validation.IAuthnRequestPostProcessor; @@ -107,120 +109,179 @@ public class AuthnRequestValidator implements IAuthnRequestPostProcessor { } // post-process requested LoA - final List reqLoA = extractLoA(authnReq); - log.trace("SP requests LoA with: {}", String.join(", ",reqLoA)); + postprocessLoaLevel(pendingReq, authnReq); + + // post-process requested LoA comparison-level + pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setLoAMachtingMode( + extractComparisonLevel(authnReq)); + + //extract information from requested attributes + extractFromRequestedAttriutes(pendingReq, authnReq); - LevelOfAssurance minimumLoAFromConfig = LevelOfAssurance.fromString(basicConfig.getBasicConfiguration( - MsEidasNodeConstants.PROP_EIDAS_REQUEST_LOA_MINIMUM_LEVEL, - EaafConstants.EIDAS_LOA_HIGH)); - if (minimumLoAFromConfig == null) { - log.warn("Can not load minimum LoA from configuration. Use LoA: {} as default", - EaafConstants.EIDAS_LOA_HIGH); - minimumLoAFromConfig = LevelOfAssurance.HIGH; + } catch (final EaafStorageException e) { + log.info("Can NOT store Authn. Req. data into pendingRequest.", e); + throw new AuthnRequestValidatorException("internal.02", null, e); - } - - log.trace("Validate requested LoA to connector configuration minimum LoA: {} ...", - minimumLoAFromConfig); - final List allowedLoA = new ArrayList<>(); - for (final String loa : reqLoA) { - try { - final LevelOfAssurance intLoa = LevelOfAssurance.fromString(loa); - String selectedLoA = EaafConstants.EIDAS_LOA_HIGH; - if (intLoa != null - && intLoa.numericValue() <= minimumLoAFromConfig.numericValue()) { - log.info("Client: {} requested LoA: {} will be upgraded to: {}", - pendingReq.getServiceProviderConfiguration().getUniqueIdentifier(), - loa, - minimumLoAFromConfig); - selectedLoA = minimumLoAFromConfig.getValue(); + } - } + } - if (!allowedLoA.contains(selectedLoA)) { - log.debug("Allow LoA: {} for Client: {}", - selectedLoA, - pendingReq.getServiceProviderConfiguration().getUniqueIdentifier()); - allowedLoA.add(selectedLoA); + private void extractFromRequestedAttriutes(IRequest pendingReq, AuthnRequest authnReq) + throws AuthnRequestValidatorException { + // validate and process requested attributes + boolean sectorDetected = false; + + final ServiceProviderConfiguration spConfig = pendingReq.getServiceProviderConfiguration( + ServiceProviderConfiguration.class); + + if (authnReq.getExtensions() != null) { + final List requestedAttributes = authnReq.getExtensions().getUnknownXMLObjects(); + for (final XMLObject reqAttrObj : requestedAttributes) { + if (reqAttrObj instanceof EaafRequestedAttributes) { + final EaafRequestedAttributes reqAttr = (EaafRequestedAttributes) reqAttrObj; + if (reqAttr.getAttributes() != null && reqAttr.getAttributes().size() != 0) { + for (final EaafRequestedAttribute el : reqAttr.getAttributes()) { + log.trace("Processing req. attribute '" + el.getName() + "' ... "); + if (el.getName().equals(PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME)) { + sectorDetected = extractBpkTargetIdentifier(el, spConfig); + + } else if (el.getName().equals(ExtendedPvpAttributeDefinitions.EID_TRANSACTION_ID_NAME)) { + extractUniqueTransactionId(el, pendingReq); + + } else { + log.debug("Ignore req. attribute: " + el.getName()); + + } + } + } else { + log.debug("No requested Attributes in Authn. Request"); + } - } catch (final IllegalArgumentException e) { - log.warn("LoA: {} is currently NOT supported and it will be ignored.", loa); - + } else { + log.info("Ignore unknown requested attribute: " + reqAttrObj.getElementQName().toString()); + } - } + } + + if (!sectorDetected) { + log.warn("Authn.Req validation FAILED. Reason: Contains NO or NO VALID target-sector information."); + throw new AuthnRequestValidatorException("pvp2.22", new Object[] { + "NO or NO VALID target-sector information" }); - pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setRequiredLoA( - allowedLoA); + } + + } - // post-process requested LoA comparison-level - final String reqLoAComperison = extractComparisonLevel(authnReq); - pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setLoAMachtingMode( - reqLoAComperison); + /** + * Extract unique transactionId from AuthnRequest. + * + * @param el Requested attribute from AuthnRequest + * @param pendingReq Current pendingRequest object (has to be of type {@link RequestImpl}) + * @return true if transactionId extraction was successful, otherwise false + */ + private boolean extractUniqueTransactionId(EaafRequestedAttribute el, IRequest pendingReq) { + if (!(pendingReq instanceof RequestImpl)) { + log.warn("Can NOT set unique transactionId from AuthnRequest,because 'PendingRequest' is NOT from Type: {}", + RequestImpl.class.getName()); + + } else { + if (el.getAttributeValues() != null && el.getAttributeValues().size() == 1) { + final String transactionId = el.getAttributeValues().get(0).getDOM().getTextContent(); + ((RequestImpl)pendingReq).setUniqueTransactionIdentifier(transactionId); + return true; - // validate and process requested attributes - boolean sectorDetected = false; + } else { + log.warn("Req. attribute '{}' contains NO or MORE THEN ONE attribute-values. Ignore full req. attribute", + el.getName()); + + } - if (authnReq.getExtensions() != null) { - final List requestedAttributes = authnReq.getExtensions().getUnknownXMLObjects(); - for (final XMLObject reqAttrObj : requestedAttributes) { - if (reqAttrObj instanceof EaafRequestedAttributes) { - final EaafRequestedAttributes reqAttr = (EaafRequestedAttributes) reqAttrObj; - if (reqAttr.getAttributes() != null && reqAttr.getAttributes().size() != 0) { - for (final EaafRequestedAttribute el : reqAttr.getAttributes()) { - log.trace("Processing req. attribute '" + el.getName() + "' ... "); - if (el.getName().equals(PvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME)) { - if (el.getAttributeValues() != null && el.getAttributeValues().size() == 1) { - final String sectorId = el.getAttributeValues().get(0).getDOM().getTextContent(); - final ServiceProviderConfiguration spConfig = pendingReq.getServiceProviderConfiguration( - ServiceProviderConfiguration.class); - - try { - spConfig.setBpkTargetIdentifier(sectorId); - sectorDetected = true; - - } catch (final EaafException e) { - log.info("Requested sector: " + sectorId + " DOES NOT match to allowed sectors for SP: " - + spConfig.getUniqueIdentifier()); - } - - } else { - log.info("Req. attribute '" + el.getName() - + "' contains NO or MORE THEN ONE attribute-values. Ignore full req. attribute"); - } - - } else { - log.debug("Ignore req. attribute: " + el.getName()); - } - - } - - } else { - log.debug("No requested Attributes in Authn. Request"); - } - - } else { - log.info("Ignore unknown requested attribute: " + reqAttrObj.getElementQName().toString()); - } + } + + return false; + } + + /** + * Extract the bPK target from requested attribute. + * + * @param el Requested attribute from AuthnRequest + * @param spConfig Service-Provider configuration for current process + * @return true if bPK target extraction was successful, otherwise false + */ + private boolean extractBpkTargetIdentifier(EaafRequestedAttribute el, ServiceProviderConfiguration spConfig) { + if (el.getAttributeValues() != null && el.getAttributeValues().size() == 1) { + final String sectorId = el.getAttributeValues().get(0).getDOM().getTextContent(); + try { + spConfig.setBpkTargetIdentifier(sectorId); + return true; + + } catch (final EaafException e) { + log.warn("Requested sector: " + sectorId + " DOES NOT match to allowed sectors for SP: " + + spConfig.getUniqueIdentifier()); + } + + } else { + log.warn("Req. attribute '" + el.getName() + + "' contains NO or MORE THEN ONE attribute-values. Ignore full req. attribute"); + } + + return false; + + } + private void postprocessLoaLevel(IRequest pendingReq, AuthnRequest authnReq) + throws AuthnRequestValidatorException { + final List reqLoA = extractLoA(authnReq); + log.trace("SP requests LoA with: {}", String.join(", ",reqLoA)); + + LevelOfAssurance minimumLoAFromConfig = LevelOfAssurance.fromString(basicConfig.getBasicConfiguration( + MsEidasNodeConstants.PROP_EIDAS_REQUEST_LOA_MINIMUM_LEVEL, + EaafConstants.EIDAS_LOA_HIGH)); + if (minimumLoAFromConfig == null) { + log.warn("Can not load minimum LoA from configuration. Use LoA: {} as default", + EaafConstants.EIDAS_LOA_HIGH); + minimumLoAFromConfig = LevelOfAssurance.HIGH; + + } + + log.trace("Validate requested LoA to connector configuration minimum LoA: {} ...", + minimumLoAFromConfig); + final List allowedLoA = new ArrayList<>(); + for (final String loa : reqLoA) { + try { + final LevelOfAssurance intLoa = LevelOfAssurance.fromString(loa); + String selectedLoA = EaafConstants.EIDAS_LOA_HIGH; + if (intLoa != null + && intLoa.numericValue() <= minimumLoAFromConfig.numericValue()) { + log.info("Client: {} requested LoA: {} will be upgraded to: {}", + pendingReq.getServiceProviderConfiguration().getUniqueIdentifier(), + loa, + minimumLoAFromConfig); + selectedLoA = minimumLoAFromConfig.getValue(); + } - } - if (!sectorDetected) { - log.info("Authn.Req validation FAILED. Reason: Contains NO or NO VALID target-sector information."); - throw new AuthnRequestValidatorException("pvp2.22", new Object[] { - "NO or NO VALID target-sector information" }); + if (!allowedLoA.contains(selectedLoA)) { + log.debug("Allow LoA: {} for Client: {}", + selectedLoA, + pendingReq.getServiceProviderConfiguration().getUniqueIdentifier()); + allowedLoA.add(selectedLoA); - } + } - } catch (final EaafStorageException e) { - log.info("Can NOT store Authn. Req. data into pendingRequest.", e); - throw new AuthnRequestValidatorException("internal.02", null, e); + } catch (final IllegalArgumentException e) { + log.warn("LoA: {} is currently NOT supported and it will be ignored.", loa); + + } } + pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setRequiredLoA( + allowedLoA); + } private String extractComparisonLevel(AuthnRequest authnReq) { diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthnRequestValidatorTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthnRequestValidatorTest.java index e34c8036..389f561e 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthnRequestValidatorTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthnRequestValidatorTest.java @@ -33,11 +33,14 @@ import org.xml.sax.SAXException; import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.connector.config.ServiceProviderConfiguration; import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; 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.modules.pvp2.api.validation.IAuthnRequestPostProcessor; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PvpSProfilePendingRequest; import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; import net.shibboleth.utilities.java.support.component.ComponentInitializationException; @@ -53,12 +56,12 @@ import net.shibboleth.utilities.java.support.component.ComponentInitializationEx @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class AuthnRequestValidatorTest { - @Autowired private IConfiguration basicConfig; + @Autowired private IConfigurationWithSP basicConfig; @Autowired protected IAuthnRequestPostProcessor authRequestValidator; private MockHttpServletRequest httpReq; private MockHttpServletResponse httpResp; - private TestRequestImpl pendingReq; + private PvpSProfilePendingRequest pendingReq; /** * jUnit class initializer. @@ -76,10 +79,11 @@ public class AuthnRequestValidatorTest { /** * jUnit test set-up. + * @throws EaafException * */ @Before - public void initialize() { + public void initialize() throws EaafException { httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); @@ -88,10 +92,12 @@ public class AuthnRequestValidatorTest { Map spConfig = new HashMap<>(); spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, RandomStringUtils.randomAlphabetic(10)); - pendingReq = new TestRequestImpl(); - pendingReq.setAuthUrl("https://localhost/ms_connector"); - pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); - pendingReq.setSpConfig(new ServiceProviderConfiguration(spConfig, basicConfig)); + pendingReq = new PvpSProfilePendingRequest(); + pendingReq.initialize(httpReq, basicConfig); + pendingReq.setPendingRequestId(RandomStringUtils.randomAlphanumeric(10)); + pendingReq.setOnlineApplicationConfiguration(new ServiceProviderConfiguration(spConfig, basicConfig)); + ((RequestImpl)pendingReq).setUniqueTransactionIdentifier(null); + } @Test @@ -128,6 +134,8 @@ public class AuthnRequestValidatorTest { Assert.assertEquals("bPK target not match", "urn:publicid:gv.at:cdid+BF", pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + Assert.assertNull("wrong transactionId", pendingReq.getUniqueTransactionIdentifier()); + } @Test @@ -164,6 +172,8 @@ public class AuthnRequestValidatorTest { Assert.assertEquals("bPK target not match", "urn:publicid:gv.at:cdid+BF", pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + Assert.assertNull("wrong transactionId", pendingReq.getUniqueTransactionIdentifier()); + } @Test @@ -200,6 +210,30 @@ public class AuthnRequestValidatorTest { Assert.assertEquals("bPK target not match", "urn:publicid:gv.at:cdid+XX", pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + Assert.assertEquals("wrong transactionId", "transId_11223344556677aabbcc", + pendingReq.getUniqueTransactionIdentifier()); + + } + + @Test + public void transactionIdWrongPendingReqType() throws AuthnRequestValidatorException, ParserConfigurationException, + SAXException, IOException, UnmarshallingException { + + Map spConfig = new HashMap<>(); + spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, RandomStringUtils.randomAlphabetic(10)); + + TestRequestImpl pendingReqLocal = new TestRequestImpl(); + pendingReqLocal.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); + pendingReqLocal.setSpConfig(new ServiceProviderConfiguration(spConfig, basicConfig)); + + AuthnRequest authReq = getAuthRequest("/data/pvp2_authn_3.xml"); + + //test + authRequestValidator.process(httpReq, pendingReqLocal, authReq, null); + + //validate + Assert.assertNull("wrong transactionId", pendingReqLocal.getUniqueTransactionIdentifier()); + } @Test @@ -214,7 +248,7 @@ public class AuthnRequestValidatorTest { } catch (AuthnRequestValidatorException e) { Assert.assertEquals("Wrong errorCode", "pvp2.22", e.getErrorId()); - + } } diff --git a/connector/src/test/resources/config/junit_config_1.properties b/connector/src/test/resources/config/junit_config_1.properties index f498cac4..3350f947 100644 --- a/connector/src/test/resources/config/junit_config_1.properties +++ b/connector/src/test/resources/config/junit_config_1.properties @@ -1,5 +1,5 @@ ## Basic service configuration -eidas.ms.context.url.prefix= +eidas.ms.context.url.prefix=http://localhost eidas.ms.context.url.request.validation=false eidas.ms.context.use.clustermode=true diff --git a/connector/src/test/resources/data/pvp2_authn_2.xml b/connector/src/test/resources/data/pvp2_authn_2.xml index 5f21af05..dbf46622 100644 --- a/connector/src/test/resources/data/pvp2_authn_2.xml +++ b/connector/src/test/resources/data/pvp2_authn_2.xml @@ -28,6 +28,10 @@ urn:publicid:gv.at:cdid+BF + + transId_11223344556677aabbcc + transId_second + diff --git a/connector/src/test/resources/data/pvp2_authn_3.xml b/connector/src/test/resources/data/pvp2_authn_3.xml index bf356da7..35e49b0f 100644 --- a/connector/src/test/resources/data/pvp2_authn_3.xml +++ b/connector/src/test/resources/data/pvp2_authn_3.xml @@ -28,6 +28,9 @@ urn:publicid:gv.at:cdid+XX + + transId_11223344556677aabbcc + -- cgit v1.2.3 From 9f684f489a2825d1c8fde371b7e71b8d7513060a Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 27 Nov 2020 09:12:22 +0100 Subject: fix a code-style issue --- .../modules/auth/eidas/v2/service/AuthBlockSigningService.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java index ad9b1082..cfaecfbb 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/service/AuthBlockSigningService.java @@ -1,6 +1,5 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.service; -import java.io.Serializable; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; @@ -172,9 +171,7 @@ public class AuthBlockSigningService { * */ @Data - public class EidasAuchBlock implements Serializable { - - private static final long serialVersionUID = -2013435642666124497L; + private static class EidasAuchBlock { @JsonProperty("challenge") private String challenge; -- cgit v1.2.3