From 0c4fe92684a707040fd7536da05945a64b309740 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 25 Feb 2021 07:54:53 +0100 Subject: Refactor tasks for MobilePhoneSignature login and tests --- .../eidas/v2/dao/SimpleMobileSignatureData.java | 18 +- ...eSignatureResponseAndSearchInRegistersTask.java | 331 ------------- .../ReceiveMobilePhoneSignatureResponseTask.java | 340 +++++++++++++ .../src/main/resources/eidas_v2_auth.beans.xml | 2 +- ...natureResponseAndSearchInRegistersTaskTest.java | 543 --------------------- ...eceiveMobilePhoneSignatureResponseTaskTest.java | 371 ++++++++++++++ 6 files changed, 719 insertions(+), 886 deletions(-) delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseTask.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java (limited to 'eidas_modules') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/dao/SimpleMobileSignatureData.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/dao/SimpleMobileSignatureData.java index 2a7beb3b..e7a5547a 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/dao/SimpleMobileSignatureData.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/dao/SimpleMobileSignatureData.java @@ -24,12 +24,12 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.dao; import lombok.Data; +import org.apache.commons.lang3.builder.EqualsBuilder; @Data public class SimpleMobileSignatureData { private String citizenCountryCode; - private String bpk; private String givenName; private String familyName; @@ -37,19 +37,15 @@ public class SimpleMobileSignatureData { /** * Compares the received authentication data from the mobile phone signature with the eid data received via eIDAS. + * * @param simpleEidasData The extracted eIDAS data * @return Returns true, if the eIDAS data matches the mobile phone signature data and false otherwise. */ public boolean equalsSimpleEidasData(SimpleEidasData simpleEidasData) { - if (!simpleEidasData.getGivenName().equals(givenName)) { - return false; - } - if (!simpleEidasData.getFamilyName().equals(familyName)) { - return false; - } - if (!simpleEidasData.getDateOfBirth().equals(dateOfBirth)) { - return false; - } - return true; + return new EqualsBuilder() + .append(simpleEidasData.getGivenName(), givenName) + .append(simpleEidasData.getFamilyName(), familyName) + .append(simpleEidasData.getDateOfBirth(), dateOfBirth) + .isEquals(); } } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.java deleted file mode 100644 index 81be04b5..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright 2021 A-SIT Plus GmbH - * AT-specific eIDAS Connector has been developed in a cooperation between EGIZ, - * A-SIT Plus GmbH, 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 "License"); - * You may not use this work except in compliance with the License. - * You may obtain a copy of the License at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * 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.modules.auth.eidas.v2.tasks; - -import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleMobileSignatureData; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthEventConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService; -import at.gv.egiz.eaaf.core.api.data.PvpAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -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.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; -import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; -import at.gv.egiz.eaaf.modules.pvp2.exception.SamlAssertionValidationExeption; -import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EaafUriCompare; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; -import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SamlVerificationEngine; -import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionValidationExeption; -import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnResponseValidationException; -import at.gv.egiz.eaaf.modules.pvp2.sp.impl.utils.AssertionAttributeExtractor; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.opensaml.core.xml.io.MarshallingException; -import org.opensaml.messaging.decoder.MessageDecodingException; -import org.opensaml.saml.saml2.core.Response; -import org.opensaml.saml.saml2.core.StatusCode; -import org.opensaml.saml.saml2.metadata.IDPSSODescriptor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.transform.TransformerException; -import java.io.IOException; -import java.util.List; -import java.util.Set; - -import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.DATA_INITIAL_REGISTER_RESULT; -import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.DATA_SIMPLE_EIDAS; -import static at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants.MODULE_NAME_FOR_LOGGING; - -/** - * Task that receives the SAML2 response from ID Austria system. - * This corresponds to Step 15 in the eIDAS Matching Concept. - * - * @author tlenz - */ -@Slf4j -@Component("ReceiveMobilePhoneSignatureResponseTask") -public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask extends AbstractAuthServletTask { - - @Autowired - private SamlVerificationEngine samlVerificationEngine; - @Autowired - private RegisterSearchService registerSearchService; - @Autowired - private IdAustriaClientAuthCredentialProvider credentialProvider; - @Autowired - IdAustriaClientAuthMetadataProvider metadataProvider; - - private static final String ERROR_PVP_03 = "sp.pvp2.03"; - private static final String ERROR_PVP_05 = "sp.pvp2.05"; - private static final String ERROR_PVP_06 = "sp.pvp2.06"; - private static final String ERROR_PVP_08 = "sp.pvp2.08"; - private static final String ERROR_PVP_10 = "sp.pvp2.10"; - private static final String ERROR_PVP_11 = "sp.pvp2.11"; - private static final String ERROR_PVP_12 = "sp.pvp2.12"; - - private static final String ERROR_MSG_00 = "Receive INVALID PVP Response from ID Austria system"; - private static final String ERROR_MSG_01 = "Processing PVP response from 'ID Austria system' FAILED."; - private static final String ERROR_MSG_02 = "PVP response decrytion FAILED. No credential found."; - private static final String ERROR_MSG_03 = "PVP response validation FAILED."; - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - try { - log.trace("Starting ReceiveMobilePhoneSignatureResponseTask"); - IDecoder decoder = loadDecoder(request); - EaafUriCompare comparator = loadComparator(request); - InboundMessage inboundMessage = decodeAndVerifyMessage(request, response, decoder, comparator); - final Pair processedMsg = validateAssertion((PvpSProfileResponse) inboundMessage); - if (processedMsg.getSecond()) { - stopProcessFromUserDecision(executionContext, request, response); - return; - } - - validateEntityId(inboundMessage); - AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(processedMsg.getFirst().getResponse()); - - /* - * SAML2 response ist bereits vollständig validiert und die Attribute können aus dem - * ausgelesen werden. - * Die AttributeNamen sind entsprechend PVP Spezifikation, z.B. PvpAttributeDefinitions.GIVEN_NAME_NAME - * - * --------------------------------------------------------------------------------------------- - * - * TODO: ab hier müssen wir wohl was anpassen - * - */ - - final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - MergedRegisterSearchResult initialSearchResult = - authProcessData.getGenericDataFromSession(DATA_INITIAL_REGISTER_RESULT, MergedRegisterSearchResult.class); - SimpleEidasData eidasData = authProcessData.getGenericDataFromSession(DATA_SIMPLE_EIDAS, SimpleEidasData.class); - - SimpleMobileSignatureData simpleMobileSignatureData = getAuthDataFromInterfederation(extractor, authProcessData); - if (!simpleMobileSignatureData.equalsSimpleEidasData(eidasData)) { - //TODO User has cheated? - throw new InvalidUserInputException(); - } - - String bpkZp = simpleMobileSignatureData.getBpk(); - MergedRegisterSearchResult result = registerSearchService.searchWithBpkZp(bpkZp); - if (result.getResultCount() == 0) { - //go to step 16 - executionContext.put(Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK, true); - return; - } else if (result.getResultCount() == 1) { - String bpk = registerSearchService.step7aKittProcess(initialSearchResult, result, eidasData, pendingReq); - authProcessData.setGenericDataToSession(Constants.DATA_RESULT_MATCHING_BPK, bpk); - return; - //node 110 - } else if (result.getResultCount() > 1) { - throw new ManualFixNecessaryException("bpkZp: " + bpkZp);// node 108 - } - - // set NeedConsent to false, because user gives consent during authentication - pendingReq.setNeedUserConsent(false); - log.info("Receive a valid assertion from IDP " + inboundMessage.getEntityID()); - } catch (final AuthnResponseValidationException e) { - throw new TaskExecutionException(pendingReq, ERROR_MSG_03, e); - } catch (MessageDecodingException | SecurityException | SamlSigningException e) { - //final String samlRequest = request.getParameter("SAMLRequest"); - //log.debug("Receive INVALID PVP Response from 'ms-specific eIDAS node': {}", - // samlRequest, null, e); - throw new TaskExecutionException(pendingReq, ERROR_MSG_00, - new AuthnResponseValidationException(ERROR_PVP_11, new Object[]{MODULE_NAME_FOR_LOGGING}, e)); - } catch (IOException | MarshallingException | TransformerException e) { - log.debug("Processing PVP response from 'ms-specific eIDAS node' FAILED.", e); - throw new TaskExecutionException(pendingReq, ERROR_MSG_01, - new AuthnResponseValidationException(ERROR_PVP_12, new Object[]{MODULE_NAME_FOR_LOGGING, e.getMessage()}, e)); - } catch (final CredentialsNotAvailableException e) { - log.debug("PVP response decrytion FAILED. No credential found.", e); - throw new TaskExecutionException(pendingReq, ERROR_MSG_02, - new AuthnResponseValidationException(ERROR_PVP_10, new Object[]{MODULE_NAME_FOR_LOGGING}, e)); - } catch (final Exception e) { - e.printStackTrace(); - log.debug("PVP response validation FAILED. Msg:" + e.getMessage(), e); - throw new TaskExecutionException(pendingReq, ERROR_MSG_03, - new AuthnResponseValidationException(ERROR_PVP_12, new Object[]{MODULE_NAME_FOR_LOGGING, e.getMessage()}, e)); - } - } - - @NotNull - private InboundMessage decodeAndVerifyMessage(HttpServletRequest request, HttpServletResponse response, - IDecoder decoder, EaafUriCompare comparator) throws Exception { - InboundMessage inboundMessage = (InboundMessage) decoder.decode(request, response, metadataProvider, - IDPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator); - if (!inboundMessage.isVerified()) { - samlVerificationEngine.verify(inboundMessage, TrustEngineFactory.getSignatureKnownKeysTrustEngine( - metadataProvider)); - inboundMessage.setVerified(true); - } - return inboundMessage; - } - - private void validateEntityId(InboundMessage inboundMessage) throws AuthnResponseValidationException { - final String msNodeEntityID = authConfig - .getBasicConfiguration(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID); - final String respEntityId = inboundMessage.getEntityID(); - if (!msNodeEntityID.equals(respEntityId)) { - log.warn("Response Issuer is not from valid 'ID Austria IDP'. Stopping ID Austria authentication ..."); - throw new AuthnResponseValidationException(ERROR_PVP_08, - new Object[]{MODULE_NAME_FOR_LOGGING, - inboundMessage.getEntityID()}); - } - } - - @NotNull - private EaafUriCompare loadComparator(HttpServletRequest request) throws AuthnResponseValidationException { - if (request.getMethod().equalsIgnoreCase("POST")) { - log.trace("Receive PVP Response from 'ID Austria system', by using POST-Binding."); - return new EaafUriCompare(pendingReq.getAuthUrl() + IdAustriaClientAuthConstants.ENDPOINT_POST); - } else if (request.getMethod().equalsIgnoreCase("GET")) { - log.trace("Receive PVP Response from 'ID Austria system', by using Redirect-Binding."); - return new EaafUriCompare(pendingReq.getAuthUrl() + IdAustriaClientAuthConstants.ENDPOINT_REDIRECT); - } else { - log.warn("Receive PVP Response from 'ID Austria system', but Binding {} is not supported.", request.getMethod()); - throw new AuthnResponseValidationException(ERROR_PVP_03, new Object[]{MODULE_NAME_FOR_LOGGING}); - } - } - - @NotNull - private IDecoder loadDecoder(HttpServletRequest request) throws AuthnResponseValidationException { - if (request.getMethod().equalsIgnoreCase("POST")) { - log.trace("Receive PVP Response from 'ID Austria system', by using POST-Binding."); - return new PostBinding(); - } else if (request.getMethod().equalsIgnoreCase("GET")) { - log.trace("Receive PVP Response from 'ID Austria system', by using Redirect-Binding."); - return new RedirectBinding(); - } else { - log.warn("Receive PVP Response from 'ID Austria system', but Binding {} is not supported.", request.getMethod()); - throw new AuthnResponseValidationException(ERROR_PVP_03, new Object[]{MODULE_NAME_FOR_LOGGING}); - } - } - - private Pair validateAssertion(PvpSProfileResponse msg) - throws IOException, MarshallingException, TransformerException, - CredentialsNotAvailableException, AuthnResponseValidationException, SamlAssertionValidationExeption { - log.debug("Start PVP21 assertion processing... "); - final Response response = (Response) msg.getResponse(); - if (response.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS)) { - samlVerificationEngine.validateAssertion(response, - credentialProvider.getMessageEncryptionCredential(), - pendingReq.getAuthUrl() + IdAustriaClientAuthConstants.ENDPOINT_METADATA, - MODULE_NAME_FOR_LOGGING); - msg.setSamlMessage(Saml2Utils.asDomDocument(response).getDocumentElement()); - revisionsLogger.logEvent(pendingReq, - IdAustriaClientAuthEventConstants.AUTHPROCESS_ID_AUSTRIA_RESPONSE_RECEIVED, - response.getID()); - return Pair.newInstance(msg, false); - } else { - log.info("Receive StatusCode {} from 'ms-specific eIDAS node'.", response.getStatus().getStatusCode().getValue()); - StatusCode subStatusCode = getSubStatusCode(response); - if (subStatusCode != null - && IdAustriaClientAuthConstants.SAML2_STATUSCODE_USERSTOP.equals(subStatusCode.getValue())) { - log.info("Find 'User-Stop operation' in SAML2 response. Stopping authentication process ... "); - return Pair.newInstance(msg, true); - } - - revisionsLogger.logEvent(pendingReq, - IdAustriaClientAuthEventConstants.AUTHPROCESS_ID_AUSTRIA_RESPONSE_RECEIVED_ERROR); - throw new AuthnResponseValidationException(ERROR_PVP_05, - new Object[]{MODULE_NAME_FOR_LOGGING, - response.getIssuer().getValue(), - response.getStatus().getStatusCode().getValue(), - response.getStatus().getStatusMessage().getMessage()}); - } - } - - /** - * Get SAML2 Sub-StatusCode if not null. - * - * @param samlResp SAML2 response - * @return Sub-StatusCode or null if it's not set - */ - private StatusCode getSubStatusCode(Response samlResp) { - if (samlResp.getStatus().getStatusCode().getStatusCode() != null - && StringUtils.isNotEmpty(samlResp.getStatus().getStatusCode().getStatusCode().getValue())) { - return samlResp.getStatus().getStatusCode().getStatusCode(); - } - return null; - } - - private SimpleMobileSignatureData getAuthDataFromInterfederation(AssertionAttributeExtractor extractor, - AuthProcessDataWrapper authProcessData) - throws EaafBuilderException { - List requiredAttributes = IdAustriaClientAuthConstants.DEFAULT_REQUIRED_PVP_ATTRIBUTE_NAMES; - SimpleMobileSignatureData result = new SimpleMobileSignatureData(); - try { - if (!extractor.containsAllRequiredAttributes(requiredAttributes)) { - log.warn("PVP Response from 'ID Austria node' contains not all requested attributes."); - throw new AssertionValidationExeption(ERROR_PVP_06, new Object[]{MODULE_NAME_FOR_LOGGING}); - } - final Set includedAttrNames = extractor.getAllIncludeAttributeNames(); - for (final String attrName : includedAttrNames) { - if (PvpAttributeDefinitions.BPK_NAME.equals(attrName)) { - result.setBpk(extractor.getSingleAttributeValue(attrName)); - } - if (PvpAttributeDefinitions.GIVEN_NAME_NAME.equals(attrName)) { - result.setGivenName(extractor.getSingleAttributeValue(attrName)); - } - if (PvpAttributeDefinitions.PRINCIPAL_NAME_NAME.equals(attrName)) { - result.setFamilyName(extractor.getSingleAttributeValue(attrName)); - } - if (PvpAttributeDefinitions.BIRTHDATE_NAME.equals(attrName)) { - result.setDateOfBirth(extractor.getSingleAttributeValue(attrName)); - } - if (PvpAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_NAME.equals(attrName)) { - authProcessData.setQaaLevel(extractor.getSingleAttributeValue(attrName)); - } - } - authProcessData.setIssueInstant(extractor.getAssertionIssuingDate()); - } catch (final AssertionValidationExeption e) { - throw new EaafBuilderException(ERROR_PVP_06, null, e.getMessage(), e); - } - return result; - } - - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseTask.java new file mode 100644 index 00000000..0f40b337 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/tasks/ReceiveMobilePhoneSignatureResponseTask.java @@ -0,0 +1,340 @@ +/* + * Copyright 2021 A-SIT Plus GmbH + * AT-specific eIDAS Connector has been developed in a cooperation between EGIZ, + * A-SIT Plus GmbH, 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 "License"); + * You may not use this work except in compliance with the License. + * You may obtain a copy of the License at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * 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.modules.auth.eidas.v2.tasks; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleMobileSignatureData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthEventConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService; +import at.gv.egiz.eaaf.core.api.data.PvpAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +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.auth.modules.AbstractAuthServletTask; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.exception.SamlAssertionValidationExeption; +import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EaafUriCompare; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SamlVerificationEngine; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionValidationExeption; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnResponseValidationException; +import at.gv.egiz.eaaf.modules.pvp2.sp.impl.utils.AssertionAttributeExtractor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.messaging.decoder.MessageDecodingException; +import org.opensaml.saml.saml2.core.Response; +import org.opensaml.saml.saml2.core.StatusCode; +import org.opensaml.saml.saml2.metadata.IDPSSODescriptor; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.transform.TransformerException; +import java.io.IOException; +import java.util.List; +import java.util.Set; + +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.DATA_INITIAL_REGISTER_RESULT; +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.DATA_SIMPLE_EIDAS; +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants.MODULE_NAME_FOR_LOGGING; + +/** + * Task that receives the SAML2 response from ID Austria system. + * This corresponds to Step 15 in the eIDAS Matching Concept. + * + * @author tlenz + */ +@Slf4j +@Component("ReceiveMobilePhoneSignatureResponseTask") +public class ReceiveMobilePhoneSignatureResponseTask extends AbstractAuthServletTask { + + private final SamlVerificationEngine samlVerificationEngine; + private final RegisterSearchService registerSearchService; + private final IdAustriaClientAuthCredentialProvider credentialProvider; + private final IdAustriaClientAuthMetadataProvider metadataProvider; + + private static final String ERROR_PVP_03 = "sp.pvp2.03"; + private static final String ERROR_PVP_05 = "sp.pvp2.05"; + private static final String ERROR_PVP_06 = "sp.pvp2.06"; + private static final String ERROR_PVP_08 = "sp.pvp2.08"; + private static final String ERROR_PVP_10 = "sp.pvp2.10"; + private static final String ERROR_PVP_11 = "sp.pvp2.11"; + private static final String ERROR_PVP_12 = "sp.pvp2.12"; + + private static final String ERROR_MSG_00 = "Receive INVALID PVP Response from ID Austria system"; + private static final String ERROR_MSG_01 = "Processing PVP response from 'ID Austria system' FAILED."; + private static final String ERROR_MSG_02 = "PVP response decryption FAILED. No credential found."; + private static final String ERROR_MSG_03 = "PVP response validation FAILED."; + + /** + * Creates the new task, with autowired dependencies from Spring. + */ + public ReceiveMobilePhoneSignatureResponseTask(SamlVerificationEngine samlVerificationEngine, + RegisterSearchService registerSearchService, + IdAustriaClientAuthCredentialProvider credentialProvider, + IdAustriaClientAuthMetadataProvider metadataProvider) { + this.samlVerificationEngine = samlVerificationEngine; + this.registerSearchService = registerSearchService; + this.credentialProvider = credentialProvider; + this.metadataProvider = metadataProvider; + } + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try { + log.trace("Starting ReceiveMobilePhoneSignatureResponseTask"); + IDecoder decoder = loadDecoder(request); + EaafUriCompare comparator = loadComparator(request); + InboundMessage inboundMessage = decodeAndVerifyMessage(request, response, decoder, comparator); + Pair processedMsg = validateAssertion((PvpSProfileResponse) inboundMessage); + if (processedMsg.getSecond()) { + stopProcessFromUserDecision(executionContext, request, response); + return; + } + + validateEntityId(inboundMessage); + AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(processedMsg.getFirst().getResponse()); + + /* + * SAML2 response ist bereits vollständig validiert und die Attribute können aus dem + * ausgelesen werden. + * Die AttributeNamen sind entsprechend PVP Spezifikation, z.B. PvpAttributeDefinitions.GIVEN_NAME_NAME + * + * --------------------------------------------------------------------------------------------- + * + * TODO: ab hier müssen wir wohl was anpassen + * + */ + + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + MergedRegisterSearchResult initialSearchResult = + authProcessData.getGenericDataFromSession(DATA_INITIAL_REGISTER_RESULT, MergedRegisterSearchResult.class); + SimpleEidasData eidasData = authProcessData.getGenericDataFromSession(DATA_SIMPLE_EIDAS, SimpleEidasData.class); + String bpkZp = extractBpkZp(extractor, authProcessData, eidasData); + + MergedRegisterSearchResult result = registerSearchService.searchWithBpkZp(bpkZp); + if (result.getResultCount() == 0) { + executionContext.put(Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK, true); + return; + } else if (result.getResultCount() == 1) { + String bpk = registerSearchService.step7aKittProcess(initialSearchResult, result, eidasData, pendingReq); + authProcessData.setGenericDataToSession(Constants.DATA_RESULT_MATCHING_BPK, bpk); + return; + } else if (result.getResultCount() > 1) { + throw new ManualFixNecessaryException("bpkZp: " + bpkZp); + } + + // set NeedConsent to false, because user gives consent during authentication + pendingReq.setNeedUserConsent(false); + log.info("Receive a valid assertion from IDP " + inboundMessage.getEntityID()); + } catch (final AuthnResponseValidationException e) { + throw new TaskExecutionException(pendingReq, ERROR_MSG_03, e); + } catch (MessageDecodingException | SecurityException | SamlSigningException e) { + //final String samlRequest = request.getParameter("SAMLRequest"); + //log.debug("Receive INVALID PVP Response from 'ms-specific eIDAS node': {}", + // samlRequest, null, e); + throw new TaskExecutionException(pendingReq, ERROR_MSG_00, + new AuthnResponseValidationException(ERROR_PVP_11, new Object[]{MODULE_NAME_FOR_LOGGING}, e)); + } catch (IOException | MarshallingException | TransformerException e) { + log.debug("Processing PVP response from 'ms-specific eIDAS node' FAILED.", e); + throw new TaskExecutionException(pendingReq, ERROR_MSG_01, + new AuthnResponseValidationException(ERROR_PVP_12, new Object[]{MODULE_NAME_FOR_LOGGING, e.getMessage()}, e)); + } catch (final CredentialsNotAvailableException e) { + log.debug("PVP response decryption FAILED. No credential found.", e); + throw new TaskExecutionException(pendingReq, ERROR_MSG_02, + new AuthnResponseValidationException(ERROR_PVP_10, new Object[]{MODULE_NAME_FOR_LOGGING}, e)); + } catch (final Exception e) { + e.printStackTrace(); + log.debug("PVP response validation FAILED. Msg:" + e.getMessage(), e); + throw new TaskExecutionException(pendingReq, ERROR_MSG_03, + new AuthnResponseValidationException(ERROR_PVP_12, new Object[]{MODULE_NAME_FOR_LOGGING, e.getMessage()}, e)); + } + } + + private String extractBpkZp(AssertionAttributeExtractor extractor, + AuthProcessDataWrapper authProcessData, + SimpleEidasData eidasData) throws EaafBuilderException, InvalidUserInputException { + SimpleMobileSignatureData simpleMobileSignatureData = getAuthDataFromInterfederation(extractor, authProcessData); + if (!simpleMobileSignatureData.equalsSimpleEidasData(eidasData)) { + //TODO User has cheated? + throw new InvalidUserInputException(); + } + return simpleMobileSignatureData.getBpk(); + } + + @NotNull + private InboundMessage decodeAndVerifyMessage(HttpServletRequest request, HttpServletResponse response, + IDecoder decoder, EaafUriCompare comparator) throws Exception { + InboundMessage inboundMessage = (InboundMessage) decoder.decode(request, response, metadataProvider, + IDPSSODescriptor.DEFAULT_ELEMENT_NAME, comparator); + if (!inboundMessage.isVerified()) { + samlVerificationEngine.verify(inboundMessage, TrustEngineFactory.getSignatureKnownKeysTrustEngine( + metadataProvider)); + inboundMessage.setVerified(true); + } + return inboundMessage; + } + + private void validateEntityId(InboundMessage inboundMessage) throws AuthnResponseValidationException { + final String msNodeEntityID = authConfig + .getBasicConfiguration(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID); + final String respEntityId = inboundMessage.getEntityID(); + if (!msNodeEntityID.equals(respEntityId)) { + log.warn("Response Issuer is not from valid 'ID Austria IDP'. Stopping ID Austria authentication ..."); + throw new AuthnResponseValidationException(ERROR_PVP_08, + new Object[]{MODULE_NAME_FOR_LOGGING, + inboundMessage.getEntityID()}); + } + } + + @NotNull + private EaafUriCompare loadComparator(HttpServletRequest request) throws AuthnResponseValidationException { + if (request.getMethod().equalsIgnoreCase("POST")) { + log.trace("Receive PVP Response from 'ID Austria system', by using POST-Binding."); + return new EaafUriCompare(pendingReq.getAuthUrl() + IdAustriaClientAuthConstants.ENDPOINT_POST); + } else if (request.getMethod().equalsIgnoreCase("GET")) { + log.trace("Receive PVP Response from 'ID Austria system', by using Redirect-Binding."); + return new EaafUriCompare(pendingReq.getAuthUrl() + IdAustriaClientAuthConstants.ENDPOINT_REDIRECT); + } else { + log.warn("Receive PVP Response from 'ID Austria system', but Binding {} is not supported.", request.getMethod()); + throw new AuthnResponseValidationException(ERROR_PVP_03, new Object[]{MODULE_NAME_FOR_LOGGING}); + } + } + + @NotNull + private IDecoder loadDecoder(HttpServletRequest request) throws AuthnResponseValidationException { + if (request.getMethod().equalsIgnoreCase("POST")) { + log.trace("Receive PVP Response from 'ID Austria system', by using POST-Binding."); + return new PostBinding(); + } else if (request.getMethod().equalsIgnoreCase("GET")) { + log.trace("Receive PVP Response from 'ID Austria system', by using Redirect-Binding."); + return new RedirectBinding(); + } else { + log.warn("Receive PVP Response from 'ID Austria system', but Binding {} is not supported.", request.getMethod()); + throw new AuthnResponseValidationException(ERROR_PVP_03, new Object[]{MODULE_NAME_FOR_LOGGING}); + } + } + + private Pair validateAssertion(PvpSProfileResponse msg) + throws IOException, MarshallingException, TransformerException, + CredentialsNotAvailableException, AuthnResponseValidationException, SamlAssertionValidationExeption { + log.debug("Start PVP21 assertion processing... "); + final Response response = (Response) msg.getResponse(); + if (response.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS)) { + samlVerificationEngine.validateAssertion(response, + credentialProvider.getMessageEncryptionCredential(), + pendingReq.getAuthUrl() + IdAustriaClientAuthConstants.ENDPOINT_METADATA, + MODULE_NAME_FOR_LOGGING); + msg.setSamlMessage(Saml2Utils.asDomDocument(response).getDocumentElement()); + revisionsLogger.logEvent(pendingReq, + IdAustriaClientAuthEventConstants.AUTHPROCESS_ID_AUSTRIA_RESPONSE_RECEIVED, + response.getID()); + return Pair.newInstance(msg, false); + } else { + log.info("Receive StatusCode {} from 'ms-specific eIDAS node'.", response.getStatus().getStatusCode().getValue()); + StatusCode subStatusCode = getSubStatusCode(response); + if (subStatusCode != null + && IdAustriaClientAuthConstants.SAML2_STATUSCODE_USERSTOP.equals(subStatusCode.getValue())) { + log.info("Find 'User-Stop operation' in SAML2 response. Stopping authentication process ... "); + return Pair.newInstance(msg, true); + } + + revisionsLogger.logEvent(pendingReq, + IdAustriaClientAuthEventConstants.AUTHPROCESS_ID_AUSTRIA_RESPONSE_RECEIVED_ERROR); + throw new AuthnResponseValidationException(ERROR_PVP_05, + new Object[]{MODULE_NAME_FOR_LOGGING, + response.getIssuer().getValue(), + response.getStatus().getStatusCode().getValue(), + response.getStatus().getStatusMessage().getMessage()}); + } + } + + /** + * Get SAML2 Sub-StatusCode if not null. + * + * @param samlResp SAML2 response + * @return Sub-StatusCode or null if it's not set + */ + private StatusCode getSubStatusCode(Response samlResp) { + if (samlResp.getStatus().getStatusCode().getStatusCode() != null + && StringUtils.isNotEmpty(samlResp.getStatus().getStatusCode().getStatusCode().getValue())) { + return samlResp.getStatus().getStatusCode().getStatusCode(); + } + return null; + } + + private SimpleMobileSignatureData getAuthDataFromInterfederation(AssertionAttributeExtractor extractor, + AuthProcessDataWrapper authProcessData) + throws EaafBuilderException { + List requiredAttributes = IdAustriaClientAuthConstants.DEFAULT_REQUIRED_PVP_ATTRIBUTE_NAMES; + SimpleMobileSignatureData result = new SimpleMobileSignatureData(); + if (!extractor.containsAllRequiredAttributes(requiredAttributes)) { + log.warn("PVP Response from 'ID Austria node' contains not all requested attributes."); + AssertionValidationExeption e = new AssertionValidationExeption(ERROR_PVP_06, + new Object[]{MODULE_NAME_FOR_LOGGING}); + throw new EaafBuilderException(ERROR_PVP_06, null, e.getMessage(), e); + } + final Set includedAttrNames = extractor.getAllIncludeAttributeNames(); + for (final String attrName : includedAttrNames) { + if (PvpAttributeDefinitions.BPK_NAME.equals(attrName)) { + result.setBpk(extractor.getSingleAttributeValue(attrName)); + } + if (PvpAttributeDefinitions.GIVEN_NAME_NAME.equals(attrName)) { + result.setGivenName(extractor.getSingleAttributeValue(attrName)); + } + if (PvpAttributeDefinitions.PRINCIPAL_NAME_NAME.equals(attrName)) { + result.setFamilyName(extractor.getSingleAttributeValue(attrName)); + } + if (PvpAttributeDefinitions.BIRTHDATE_NAME.equals(attrName)) { + result.setDateOfBirth(extractor.getSingleAttributeValue(attrName)); + } + if (PvpAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_NAME.equals(attrName)) { + authProcessData.setQaaLevel(extractor.getSingleAttributeValue(attrName)); + } + } + authProcessData.setIssueInstant(extractor.getAssertionIssuingDate()); + return result; + } + + +} 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 34046e55..ed086493 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 @@ -121,7 +121,7 @@ scope="prototype" /> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.03", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } - - @Test - public void httpGetNoMessage() { - httpReq = new MockHttpServletRequest("GET", "https://localhost/authhandler"); - RequestContextHolder.resetRequestAttributes(); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostNoMessage() { - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } - - @Test - public void httpPostMessageNotSigned() throws IOException { - - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - IOUtils.toByteArray(ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.class - .getResourceAsStream( - "/data/Response_without_sig_classpath_entityid.xml")))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostMessageWrongDestinationEndpoint() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - TransformerException, MarshallingException { - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_wrong_destination_endpoint.xml", - credentialProvider.getMessageSigningCredential(), true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedNoMetadata() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.11", ((EaafException) e.getOriginalException()).getErrorId()); - } - - @Test - public void httpPostValidSignedAssertionOutDated() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), false); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedAssertionFromWrongIdp() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, - "http://wrong.idp/" + RandomStringUtils.randomAlphabetic(5)); - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.08", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedAssertionMissingAttributes() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedWithError() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedWitUserStopErrorCode() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error_userstop.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - // perform test - task.execute(pendingReq, executionContext); - - // validate state - assertTrue("process not cancelled", executionContext.isProcessCancelled()); - assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); - assertFalse("should not authenticated", pendingReq.isAuthenticated()); - - } - - @Test - public void httpPostValidSignedWithErrorAndNoSubCode() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error_without_subcode.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - try { - task.execute(pendingReq, executionContext); - fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); - } - } - - @Test - public void httpPostValidSignedWithErrorAndEmptySubCode() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error_empty_subcode.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - try { - task.execute(pendingReq, executionContext); - fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); - - } - } - - @Test - public void httpPostValidSignedAssertionEidValid() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_EID.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - // put SimpleEidasData in session - final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - final SimpleEidasData eidData = new SimpleEidasData(); - eidData.setFamilyName("Mustermann"); - eidData.setGivenName("Max"); - eidData.setDateOfBirth("1940-01-01"); - authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - - // perform task - task.execute(pendingReq, executionContext); - - // validate state - final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); - assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); - assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); - - //TODO: - - } - - @Test - public void httpPostValidSignedAssertionEidValidButNameMissmatch() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_EID.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - // put SimpleEidasData in session - final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - final SimpleEidasData eidData = new SimpleEidasData(); - eidData.setFamilyName("Mustermann1"); - eidData.setGivenName("Max"); - eidData.setDateOfBirth("1940-01-01"); - authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - - // perform task - try { - task.execute(pendingReq, executionContext); - fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertTrue(e.getOriginalException().getCause() instanceof InvalidUserInputException); - } - - } - - private Response initializeResponse(String idpEntityId, String responsePath, EaafX509Credential credential, - boolean validConditions) throws SamlSigningException, XMLParserException, UnmarshallingException, - Pvp2MetadataException { - - final Response response = (Response) XMLObjectSupport.unmarshallFromInputStream( - XMLObjectProviderRegistrySupport.getParserPool(), - ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.class.getResourceAsStream( - responsePath)); - response.setIssueInstant(DateTime.now()); - final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class); - issuer.setValue(idpEntityId); - response.setIssuer(issuer); - - if (validConditions) { - response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5)); - - } - - return Saml2Utils.signSamlObject(response, credential, true); - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java new file mode 100644 index 00000000..5ea7b59b --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java @@ -0,0 +1,371 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveMobilePhoneSignatureResponseTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyPendingRequest; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +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.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnResponseValidationException; +import net.shibboleth.utilities.java.support.xml.ParserPool; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.saml2.core.Issuer; +import org.opensaml.saml.saml2.core.Response; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.xml.transform.TransformerException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Objects; + +import static org.junit.Assert.*; +import static org.springframework.util.Assert.isInstanceOf; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" +}) +public class ReceiveMobilePhoneSignatureResponseTaskTest { + + private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; + + @Autowired + protected MsConnectorDummyConfigMap authConfig; + @Autowired + private IdAustriaClientAuthMetadataProvider metadataProvider; + @Autowired + private IdAustriaClientAuthCredentialProvider credentialProvider; + @Autowired + private PvpMetadataResolverFactory metadataFactory; + @Autowired + private ReceiveMobilePhoneSignatureResponseTask task; + + private final ExecutionContext executionContext = new ExecutionContextImpl(); + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private DummyPendingRequest pendingReq; + + /** + * JUnit class initializer. + * + * @throws Exception In case of an OpenSAML3 initialization error + */ + @BeforeClass + public static void initialize() throws Exception { + EaafOpenSaml3xInitializer.eaafInitialize(); + } + + /** + * jUnit test set-up. + * + * @throws Exception In case of an set-up error + */ + @Before + public void setUp() throws Exception { + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpReq.setScheme("https"); + httpReq.setServerPort(443); + httpReq.setContextPath("/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, METADATA_PATH); + + DummyOA oaParam = new DummyOA(); + oaParam.setUniqueAppId("http://test.com/test"); + oaParam.setTargetIdentifier(EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); + + pendingReq = new DummyPendingRequest(); + pendingReq.initialize(httpReq, authConfig); + pendingReq.setPendingRequestId(RandomStringUtils.randomAlphanumeric(10)); + pendingReq.setOnlineApplicationConfiguration(oaParam); + + metadataProvider.fullyDestroy(); + } + + @Test + public void unsupportedHttpMethod() { + httpReq = new MockHttpServletRequest("PUT", "https://localhost/authhandler"); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.03", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpGetNoMessage() { + httpReq = new MockHttpServletRequest("GET", "https://localhost/authhandler"); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + + @Test + public void httpPostNoMessage() { + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostMessageNotSigned() throws IOException { + byte[] bytes = IOUtils.toByteArray(ReceiveMobilePhoneSignatureResponseTask.class + .getResourceAsStream("/data/Response_without_sig_classpath_entityid.xml")); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString(bytes)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + + @Test + public void httpPostMessageWrongDestinationEndpoint() throws Exception { + initResponse("/data/Response_with_wrong_destination_endpoint.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + + @Test + public void httpPostValidSignedNoMetadata() throws Exception { + initResponse("/data/Response_without_sig_classpath_entityid.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.11", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionOutDated() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_classpath_entityid.xml", false); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionFromWrongIdp() throws Exception { + authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, + "http://wrong.idp/" + RandomStringUtils.randomAlphabetic(5)); + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_classpath_entityid.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.08", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionMissingAttributes() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_classpath_entityid.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedWithError() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedWitUserStopErrorCode() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error_userstop.xml", true); + + task.execute(pendingReq, executionContext); + + assertTrue("process not cancelled", executionContext.isProcessCancelled()); + assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); + assertFalse("should not authenticated", pendingReq.isAuthenticated()); + } + + @Test + public void httpPostValidSignedWithErrorAndNoSubCode() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error_without_subcode.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedWithErrorAndEmptySubCode() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error_empty_subcode.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionEidValidButNameMismatch() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_with_EID.xml", true); + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + eidData.setFamilyName(eidData.getFamilyName() + "notmatching"); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + isInstanceOf(InvalidUserInputException.class, e.getOriginalException().getCause()); + } + + @Test + public void httpPostValidSignedAssertionEidValid() throws Exception { + // klar darstellen: was ist input, was ist dann expected output ... eigentlich für alle tasks! + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_with_EID.xml", true); + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + + task.execute(pendingReq, executionContext); + + AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); + assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); + assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); + + //TODO this is the good case + } + + @NotNull + private SimpleEidasData createEidasDataMatchingToSamlResponse() { + // data from "/data/Response_with_EID.xml" + SimpleEidasData result = new SimpleEidasData(); + result.setFamilyName("Mustermann"); + result.setGivenName("Max"); + result.setDateOfBirth("1940-01-01"); + return result; + } + + private void addSamlResponseToHttpReq(Response response) throws TransformerException, IOException, MarshallingException { + String node = DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)); + String base64encoded = Base64.getEncoder().encodeToString(node.getBytes(StandardCharsets.UTF_8)); + httpReq.addParameter("SAMLResponse", base64encoded); + } + + private void initResponse(String responsePath, boolean validConditions) throws Exception { + InputStream inputStream = ReceiveMobilePhoneSignatureResponseTaskTest.class.getResourceAsStream(responsePath); + ParserPool parserPool = Objects.requireNonNull(XMLObjectProviderRegistrySupport.getParserPool()); + Response response = (Response) XMLObjectSupport.unmarshallFromInputStream(parserPool, inputStream); + response.setIssueInstant(DateTime.now()); + Issuer issuer = Saml2Utils.createSamlObject(Issuer.class); + issuer.setValue("classpath:/data/idp_metadata_classpath_entity.xml"); + response.setIssuer(issuer); + if (validConditions) { + response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5)); + } + Response signedResponse = Saml2Utils.signSamlObject(response, credentialProvider.getMessageSigningCredential(), true); + addSamlResponseToHttpReq(signedResponse); + } + +} -- cgit v1.2.3