diff options
| author | Thomas <> | 2021-09-02 09:01:27 +0200 | 
|---|---|---|
| committer | Thomas <> | 2021-09-02 09:01:27 +0200 | 
| commit | 3d758efdb2d1f455222773d1b5d2cba91a32f8ad (patch) | |
| tree | eead4117719b5fc5ebd824e610ca46f14b8322df /eidas_modules/authmodule-eIDAS-v2/src/test | |
| parent | af4097de42e0208d19fdcee7bbfc1406b64c17c7 (diff) | |
| parent | 34094edfbf91cf445dbeae12b1b63cbfef543244 (diff) | |
| download | National_eIDAS_Gateway-3d758efdb2d1f455222773d1b5d2cba91a32f8ad.tar.gz National_eIDAS_Gateway-3d758efdb2d1f455222773d1b5d2cba91a32f8ad.tar.bz2 National_eIDAS_Gateway-3d758efdb2d1f455222773d1b5d2cba91a32f8ad.zip | |
Merge branch 'feature/matching_rebased' into feature/matching_base
Diffstat (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test')
58 files changed, 5937 insertions, 723 deletions
| diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasSignalServletTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasSignalServletTest.java index 62d5c556..f23d61db 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasSignalServletTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasSignalServletTest.java @@ -14,7 +14,6 @@ import org.junit.Assert;  import org.junit.Before;  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; @@ -47,12 +46,10 @@ import eu.eidas.auth.commons.tx.BinaryLightToken;  import eu.eidas.specificcommunication.exception.SpecificCommunicationException;  @RunWith(SpringJUnit4ClassRunner.class) -@PrepareForTest(CreateIdentityLinkTask.class)  @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml",      "/SpringTest-context_basic_mapConfig.xml"}) -@EnableWebMvc  public class EidasSignalServletTest {    @Autowired private MsConnectorDummyConfigMap basicConfig; @@ -61,14 +58,14 @@ public class EidasSignalServletTest {    @Autowired private ITransactionStorage transStore;    @Autowired private DummyProtocolAuthService protAuthService;    @Autowired private DummySpecificCommunicationService connector; -   -   + +    private MockHttpServletRequest httpReq;    private MockHttpServletResponse httpResp;    private TestRequestImpl pendingReq;    private MsConnectorDummySpConfiguration oaParam; -   -    + +    /**     * jUnit test set-up.     */ @@ -78,7 +75,7 @@ public class EidasSignalServletTest {      httpResp = new MockHttpServletResponse();      RequestContextHolder.resetRequestAttributes();      RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); -     +      final Map<String, String> spConfig = new HashMap<>();      spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp");      spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); @@ -92,51 +89,51 @@ public class EidasSignalServletTest {      pendingReq.setAuthUrl("http://test.com/");      pendingReq.setTransactionId("avaasbav");      pendingReq.setPiiTransactionId(RandomStringUtils.randomAlphanumeric(10)); -    +      connector.setiLightResponse(null); -     -     + +    } -   +    @Test    public void noResponsToken() throws IOException, EaafException {      //set-up -          +      //execute test      controller.restoreEidasAuthProcess(httpReq, httpResp); -        +      //validate state      Assert.assertNull("eIDAS response", httpReq.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE));      Assert.assertNotNull("missing error", protAuthService.getException()); -    Assert.assertEquals("Wrong errorId", "auth.26",  +    Assert.assertEquals("Wrong errorId", "auth.26",          ((EaafException) protAuthService.getException()).getErrorId()); -     +    } -   +    @Test    public void unknownResponseToken() throws IOException, EaafException {      //set-up -    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),  +    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),          RandomStringUtils.randomAlphanumeric(10)); -          +      //execute test      controller.restoreEidasAuthProcess(httpReq, httpResp); -        +      //validate state      Assert.assertNull("eIDAS response", httpReq.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE));      Assert.assertNotNull("missing error", protAuthService.getException()); -    Assert.assertEquals("Wrong errorId", "auth.26",  +    Assert.assertEquals("Wrong errorId", "auth.26",          ((EaafException) protAuthService.getException()).getErrorId()); -     +    } -   +    @Test    public void withRelayState() throws IOException, EaafException, SpecificCommunicationException { -    //set-up                  -    String relayState = RandomStringUtils.randomAlphanumeric(10);     +    //set-up +    String relayState = RandomStringUtils.randomAlphanumeric(10);      pendingReq.setPendingReqId(relayState);      storage.storePendingRequest(pendingReq); -     +      Builder iLightResponse = new AuthenticationResponse.Builder();      iLightResponse.id("_".concat(Random.nextHexRandom16()))          .issuer(RandomStringUtils.randomAlphabetic(10)) @@ -145,37 +142,37 @@ public class EidasSignalServletTest {          .inResponseTo("_".concat(Random.nextHexRandom16()))          .subjectNameIdFormat("afaf")          .relayState(relayState); -      +      AuthenticationResponse eidasResp = iLightResponse.build(); -    BinaryLightToken token = connector.putResponse(eidasResp);     -    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),  +    BinaryLightToken token = connector.putResponse(eidasResp); +    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),          Base64.getEncoder().encodeToString(token.getTokenBytes())); -     +      //execute test      controller.restoreEidasAuthProcess(httpReq, httpResp); -        -     + +      //validate state      Assert.assertNotNull("eIDAS response", httpReq.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE)); -    Assert.assertEquals("wrong eIDAS response", eidasResp,  +    Assert.assertEquals("wrong eIDAS response", eidasResp,          httpReq.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE)); -     -    Assert.assertNotNull("missing error", protAuthService.getException());     -    Assert.assertEquals("Wrong errorId", "PendingRequest object is not of type 'RequestImpl.class'",  + +    Assert.assertNotNull("missing error", protAuthService.getException()); +    Assert.assertEquals("Wrong errorId", "PendingRequest object is not of type 'RequestImpl.class'",          ((EaafException) protAuthService.getException()).getErrorId()); -     +    } -   +    @Test    public void withOutRelayStateMissingPendingReq() throws IOException, EaafException, SpecificCommunicationException { -    //set-up                  -    String pendingReqId = RandomStringUtils.randomAlphanumeric(10);     +    //set-up +    String pendingReqId = RandomStringUtils.randomAlphanumeric(10);      pendingReq.setPendingReqId(pendingReqId);      storage.storePendingRequest(pendingReq); -     +      String inResponseTo = "_".concat(Random.nextHexRandom16()); -     +      Builder iLightResponse = new AuthenticationResponse.Builder();      iLightResponse.id("_".concat(Random.nextHexRandom16()))          .issuer(RandomStringUtils.randomAlphabetic(10)) @@ -183,35 +180,35 @@ public class EidasSignalServletTest {          .statusCode(Constants.SUCCESS_URI)          .inResponseTo(inResponseTo)          .subjectNameIdFormat("afaf"); -      +      AuthenticationResponse eidasResp = iLightResponse.build(); -    BinaryLightToken token = connector.putResponse(eidasResp);     -    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),  +    BinaryLightToken token = connector.putResponse(eidasResp); +    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),          Base64.getEncoder().encodeToString(token.getTokenBytes())); -     +      //execute test      controller.restoreEidasAuthProcess(httpReq, httpResp); -        -     + +      //validate state      Assert.assertNull("eIDAS response", httpReq.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE));      Assert.assertNotNull("missing error", protAuthService.getException()); -    Assert.assertEquals("Wrong errorId", "auth.26",  +    Assert.assertEquals("Wrong errorId", "auth.26",          ((EaafException) protAuthService.getException()).getErrorId()); -     +    } -   +    @Test    public void withInResponseToElement() throws IOException, EaafException, SpecificCommunicationException { -    //set-up                  -    String pendingReqId = RandomStringUtils.randomAlphanumeric(10);     +    //set-up +    String pendingReqId = RandomStringUtils.randomAlphanumeric(10);      pendingReq.setPendingReqId(pendingReqId);      storage.storePendingRequest(pendingReq); -             +      String inResponseTo = "_".concat(Random.nextHexRandom16());      transStore.put(inResponseTo, pendingReqId, -1); -     +      Builder iLightResponse = new AuthenticationResponse.Builder();      iLightResponse.id("_".concat(Random.nextHexRandom16()))          .issuer(RandomStringUtils.randomAlphabetic(10)) @@ -219,26 +216,26 @@ public class EidasSignalServletTest {          .statusCode(Constants.SUCCESS_URI)          .inResponseTo(inResponseTo)          .subjectNameIdFormat("afaf"); -      +      AuthenticationResponse eidasResp = iLightResponse.build(); -    BinaryLightToken token = connector.putResponse(eidasResp);     -    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),  +    BinaryLightToken token = connector.putResponse(eidasResp); +    httpReq.setParameter(EidasParameterKeys.TOKEN.toString(),          Base64.getEncoder().encodeToString(token.getTokenBytes())); -     +      //execute test      controller.restoreEidasAuthProcess(httpReq, httpResp); -        -     + +      //validate state      Assert.assertNotNull("eIDAS response", httpReq.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE)); -    Assert.assertEquals("wrong eIDAS response", eidasResp,  +    Assert.assertEquals("wrong eIDAS response", eidasResp,          httpReq.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE)); -     -    Assert.assertNotNull("missing error", protAuthService.getException());     -    Assert.assertEquals("Wrong errorId", "PendingRequest object is not of type 'RequestImpl.class'",  + +    Assert.assertNotNull("missing error", protAuthService.getException()); +    Assert.assertEquals("Wrong errorId", "PendingRequest object is not of type 'RequestImpl.class'",          ((EaafException) protAuthService.getException()).getErrorId()); -     +    } -   +  } 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/clients/SzrClientProductionTest.java index 1e7ff369..a5b83b13 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/clients/SzrClientProductionTest.java @@ -21,18 +21,21 @@   * that you distribute must include a readable copy of the "NOTICE" text file.  */ -package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchProviderException; -import java.util.List; +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.clients; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.clients.szr.SzrClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasSAuthenticationException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicationException; +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.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.exceptions.EaafParserException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser;  import org.apache.commons.lang3.RandomStringUtils;  import org.apache.commons.lang3.StringUtils;  import org.bouncycastle.util.encoders.Base64; -import org.joda.time.DateTime;  import org.junit.Assert;  import org.junit.Ignore;  import org.junit.Test; @@ -44,27 +47,10 @@ import org.springframework.test.annotation.IfProfileValue;  import org.springframework.test.context.ContextConfiguration;  import org.springframework.test.context.TestPropertySource;  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.Base64Utils;  import org.w3c.dom.Element; - -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.EidasSAuthenticationException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicationException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.szr.SzrClient; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.EidasResponseUtils; -import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; -import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType; -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.auth.data.IIdentityLink; -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 szrservices.IdentityLinkType; -import szrservices.PersonInfoType; -import szrservices.SZRException_Exception; -import szrservices.TravelDocumentType; + +import java.util.List;  @IfProfileValue(name = "spring.profiles.active", value = "devEnvironment") @@ -76,20 +62,14 @@ import szrservices.TravelDocumentType;      //"classpath:/application.properties",      "file:/home/tlenz/Projekte/config/ms_connector/default_config.properties",      }) -public class SzrClientTestProduction { -  private static final Logger log = LoggerFactory.getLogger(SzrClientTestProduction.class); +public class SzrClientProductionTest { +  private static final Logger log = LoggerFactory.getLogger(SzrClientProductionTest.class);    @Autowired    SzrClient szrClient;    @Autowired    IConfiguration basicConfig; -  private static final String givenName = "Franz"; -  private static final String familyName = "Mustermann"; -  // private static final String dateOfBirth = "1989-05-05"; -  private static final String dateOfBirth = "1989-05-04"; -  private static final String eIDASeID = "IS/AT/1234ffgsdfg56789ABCDEF"; -    private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP";    @Test @@ -98,38 +78,29 @@ public class SzrClientTestProduction {    }    @Test -  public void getVsz() throws SzrCommunicationException, EidasSAuthenticationException {     -    String vsz = szrClient.getEncryptedStammzahl(getPersonInfo());    +  public void getVsz() throws EidasSAuthenticationException { +    String vsz = szrClient.getEncryptedStammzahl(getEidData());      Assert.assertNotNull("vsz", vsz); -         +    }    @Test -  public void getEidasBind() throws SzrCommunicationException, EidasSAuthenticationException {     +  public void getEidasBind() throws EidasSAuthenticationException {      String vsz = RandomStringUtils.randomAlphanumeric(10);      String bindingPubKey = Base64.toBase64String(RandomStringUtils.random(20).getBytes());      String eidStatus = "urn:eidgvat:eid.status.eidas"; -    ErnbEidData eidData = new ErnbEidData(); -    eidData.setFamilyName(familyName); -    eidData.setGivenName(givenName); -    eidData.setDateOfBirth(new DateTime()); -    eidData.setCitizenCountryCode("IS"); -    eidData.setPseudonym("1234sdgsdfg56789ABCDEF"); -     -     -    String eidasBind = szrClient.getEidsaBind(vsz, bindingPubKey, eidStatus, eidData);    -     + +    String eidasBind = szrClient.getEidasBind(vsz, bindingPubKey, eidStatus, getEidData()); +      Assert.assertNotNull("eidasBind", eidasBind); -         +    } -   -   + +    @Test -  public void getIdentityLinkRawMode() throws SZRException_Exception, EaafParserException, -      NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException { +  public void getIdentityLinkRawMode() throws EaafParserException, EidasSAuthenticationException {      log.debug("Starting connecting SZR Gateway"); -    final IdentityLinkType result = szrClient.getIdentityLinkInRawMode( -        getPersonInfo()); +    final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(getEidData());      final Element idlFromSzr = (Element) result.getAssertion();      final IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser(idlFromSzr).parseIdentityLink(); @@ -173,11 +144,10 @@ public class SzrClientTestProduction {    @Ignore    @Test -  public void getBpkTest() throws SZRException_Exception, EidasSAuthenticationException { -    final List<String> bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, -        basicConfig.getBasicConfiguration( -            Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, -            "no VKZ defined")); +  public void getBpkTest() throws EidasSAuthenticationException { +    String vkz = basicConfig.getBasicConfiguration( +        Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined"); +    final List<String> bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, vkz);      if (bPK.isEmpty()) {        throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); @@ -190,47 +160,14 @@ public class SzrClientTestProduction {    } -  private String createHashFromUniqueId(String uniqueId) throws EidasSAuthenticationException { -    try { -      final MessageDigest md = MessageDigest.getInstance("SHA-256"); -      final byte[] hash = md.digest(uniqueId.getBytes("UTF-8")); -      final String hashBase64 = new String(Base64Utils.encode(hash), "UTF-8").replaceAll("\r\n", ""); -      return hashBase64; - -    } catch (final Exception ex) { -      throw new EidasSAuthenticationException("internal.03", new Object[] {}, ex); - -    } +  private SimpleEidasData getEidData() { +    return SimpleEidasData.builder() +        .familyName("Mustermann") +        .givenName("Franz") +        .dateOfBirth("1989-05-04") +        .citizenCountryCode("IS") +        .pseudonym("1234ffgsdfg56789ABCDEF") +        .build();    } -  private PersonInfoType getPersonInfo() throws EidasSAuthenticationException { -    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); - -    // parse some eID attributes -    final Triple<String, String, String> eIdentifier = -        EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); -    final String uniqueId = createHashFromUniqueId(eIdentifier.getThird()); -    final String citizenCountry = eIdentifier.getFirst(); - -    // person information -    personName.setFamilyName(familyName); -    personName.setGivenName(givenName); -    naturalPerson.setDateOfBirth(dateOfBirth); -    eDocument.setIssuingCountry(citizenCountry); -    eDocument.setDocumentNumber(uniqueId); - -    // eID document information -    eDocument.setDocumentType(basicConfig.getBasicConfiguration( -        Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, -        Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); - -    return personInfo; -  }  } 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/clients/SzrClientTest.java index 786b10de..ee1ecf9f 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/clients/SzrClientTest.java @@ -21,16 +21,13 @@   * that you distribute must include a readable copy of the "NOTICE" text file.   */ -package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.clients;  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.List;  import javax.xml.bind.JAXBContext; @@ -43,45 +40,34 @@ import org.apache.commons.io.IOUtils;  import org.apache.commons.lang3.RandomStringUtils;  import org.apache.commons.lang3.StringUtils;  import org.apache.cxf.binding.soap.SoapFault; -import org.joda.time.DateTime; -import org.jose4j.lang.JoseException;  import org.junit.Assert;  import org.junit.Before;  import org.junit.Ignore;  import org.junit.Rule;  import org.junit.Test;  import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.test.annotation.DirtiesContext;  import org.springframework.test.annotation.DirtiesContext.ClassMode;  import org.springframework.test.context.ContextConfiguration;  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.Base64Utils;  import org.w3c.dom.Element;  import org.xml.sax.SAXException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper;  import com.github.skjolber.mockito.soap.SoapServiceRule;  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.ErnbEidData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.clients.szr.SzrClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData;  import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasSAuthenticationException;  import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.SzrCommunicationException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.szr.SzrClient; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.EidasResponseUtils; -import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; -import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType;  import at.gv.egiz.eaaf.core.api.data.EaafConstants;  import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink;  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 lombok.extern.slf4j.Slf4j;  import szrservices.GetBPKFromStammzahlEncryptedResponse;  import szrservices.GetBPKFromStammzahlEncryptedResponseType;  import szrservices.GetIdentityLinkEidasResponse; @@ -92,29 +78,21 @@ import szrservices.SZRException_Exception;  import szrservices.SignContentEntry;  import szrservices.SignContentResponse;  import szrservices.SignContentResponseType; -import szrservices.TravelDocumentType;  @RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml",      "/SpringTest-context_basic_mapConfig.xml"})  @DirtiesContext(classMode = ClassMode.AFTER_CLASS) +@Slf4j  public class SzrClientTest { -  private static final Logger log = LoggerFactory.getLogger(SzrClientTest.class);    @Autowired SzrClient szrClient;    @Autowired MsConnectorDummyConfigMap basicConfig; -  private static ObjectMapper mapper = new ObjectMapper(); -   -  private static final String givenName = "Franz"; -  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";    private SZR szrMock = null; -  ErnbEidData eidData = null;    @Rule    public SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -126,25 +104,17 @@ public class SzrClientTest {    public void initializer() {      if (szrMock == null) {        szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); -      } -     -    eidData = new ErnbEidData(); -    eidData.setFamilyName(familyName); -    eidData.setGivenName(givenName); -    eidData.setDateOfBirth(new DateTime()); -    eidData.setCitizenCountryCode("IS"); -    eidData.setPseudonym("1234sdgsdfg56789ABCDEF"); -     +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.eidasbind.mds.inject", "false"); -       +        }    @Test -  public void getStammzahlenEcryptedTest() throws JAXBException, SZRException_Exception, SzrCommunicationException { +  public void getStammzahlenEcryptedTest() throws SZRException_Exception, SzrCommunicationException {      final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse();      final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType();      szrResponse.getOut().add(result1); @@ -155,13 +125,13 @@ public class SzrClientTest {      //        .thenReturn(Arrays.asList(result1));      when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(result1.getKey()); -    String stammzahlEncrypted = szrClient.getEncryptedStammzahl(new PersonInfoType()); +    String stammzahlEncrypted = szrClient.getEncryptedStammzahl(getEidData());      Assert.assertEquals("bcBind not match", result1.getKey(), stammzahlEncrypted);      when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(null);      try { -      stammzahlEncrypted = szrClient.getEncryptedStammzahl(new PersonInfoType()); +      szrClient.getEncryptedStammzahl(getEidData());      } catch (SzrCommunicationException e) {        Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01"));      } @@ -181,45 +151,45 @@ public class SzrClientTest {      when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content);      final String bcBind = szrClient -        .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -                   RandomStringUtils.randomAlphabetic(10), eidData); +        .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), +                   RandomStringUtils.randomAlphabetic(10), getEidData());      Assert.assertNotNull("bcBind is null", bcBind);      Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); -     +    }    @Test    public void eidasBindNull() throws SZRException_Exception {      when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(null); -     -    try {       + +    try {        szrClient -          .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -                     RandomStringUtils.randomAlphabetic(10), eidData); +          .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), +                     RandomStringUtils.randomAlphabetic(10), getEidData());      } catch (SzrCommunicationException e) {        Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); -       -    }     + +    }    } -   +    @Test    public void eidasBindInvalidResponse() throws SZRException_Exception {      final SignContentEntry result2 = new SignContentEntry();      final SignContentResponseType content1 = new SignContentResponseType();      content1.getOut().add(result2);      when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content1); -     +      try {        szrClient -          .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -                     RandomStringUtils.randomAlphabetic(10), eidData); +          .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), +                     RandomStringUtils.randomAlphabetic(10), getEidData());      } catch (SzrCommunicationException e) {        Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); -       +      }    } -   +    public void eidasBindEmptyResponse() throws SZRException_Exception {      final SignContentEntry result2 = new SignContentEntry();      final SignContentResponseType content1 = new SignContentResponseType(); @@ -227,20 +197,19 @@ public class SzrClientTest {      result2.setKey("bcBindReq");      result2.setValue("");      when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content1); -     +      try {        szrClient -          .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -                     RandomStringUtils.randomAlphabetic(10), eidData); +          .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), +                     RandomStringUtils.randomAlphabetic(10), getEidData());      } catch (SzrCommunicationException e) {        Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); -       -    }     + +    }    } -   +    @Test -  public void eidasBindValid() throws SZRException_Exception, SzrCommunicationException, JsonMappingException,  -      JsonProcessingException, JoseException { +  public void eidasBindValid() throws SZRException_Exception, SzrCommunicationException {      final SignContentResponse szrResponse = new SignContentResponse();      final SignContentEntry result1 = new SignContentEntry();      final SignContentResponseType content = new SignContentResponseType(); @@ -253,19 +222,18 @@ public class SzrClientTest {      when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content);      final String bcBind = szrClient -        .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -                   RandomStringUtils.randomAlphabetic(10), eidData); +        .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), +                   RandomStringUtils.randomAlphabetic(10), getEidData());      Assert.assertNotNull("bcBind is null", bcBind);      Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); -        +    }    @Test -  public void eidasBindValidWithMds() throws SZRException_Exception, SzrCommunicationException, JoseException,  -      JsonMappingException, JsonProcessingException { +  public void eidasBindValidWithMds() throws SZRException_Exception, SzrCommunicationException {      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.eidasbind.mds.inject", "true"); -     +      final SignContentResponse szrResponse = new SignContentResponse();      final SignContentEntry result1 = new SignContentEntry();      final SignContentResponseType content = new SignContentResponseType(); @@ -278,23 +246,22 @@ public class SzrClientTest {      when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content);      final String bcBind = szrClient -        .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -                   RandomStringUtils.randomAlphabetic(10), eidData); +        .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), +                   RandomStringUtils.randomAlphabetic(10), getEidData());      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 { +      throws SZRException_Exception, EaafParserException, 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(getEidData());        Assert.assertNotNull(result);        Assert.assertNotNull(result.getAssertion()); @@ -322,13 +289,12 @@ public class SzrClientTest {    @Test    public void getIdentityLinkRawModeErrorTravelerDocExists() -      throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, -      EidasSAuthenticationException, JAXBException, ParserConfigurationException, SAXException { +      throws SZRException_Exception, IOException, ParserConfigurationException, SAXException {      setSzrExceptionIdentityLink("/data/szr/szr_resp_error_travelerdocexists.xml");      try {        log.debug("Starting connecting SZR Gateway"); -      szrClient.getIdentityLinkInRawMode(getPersonInfo()); +      szrClient.getIdentityLinkInRawMode(getEidData());        Assert.fail();      } catch (final SzrCommunicationException e) { @@ -347,8 +313,8 @@ public class SzrClientTest {    @Ignore    @Test -  public void getBpkTest() throws SZRException_Exception, EidasSAuthenticationException { -    final List<String> bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, basicConfig +  public void getBpkTest() throws EidasSAuthenticationException { +    final List<String> bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, basicConfig          .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined"));      if (bPK.isEmpty()) { @@ -368,6 +334,7 @@ public class SzrClientTest {    } +  @SuppressWarnings("SameParameterValue")    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, @@ -380,8 +347,9 @@ public class SzrClientTest {    } +  @SuppressWarnings("SameParameterValue")    private void setSzrExceptionIdentityLink(String responseXmlPath) -      throws JAXBException, ParserConfigurationException, SAXException, IOException, SZRException_Exception { +      throws 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( @@ -393,47 +361,15 @@ public class SzrClientTest {    } -  private String createHashFromUniqueId(String uniqueId) throws EidasSAuthenticationException { -    try { -      final MessageDigest md = MessageDigest.getInstance("SHA-256"); -      final byte[] hash = md.digest(uniqueId.getBytes("UTF-8")); -      final String hashBase64 = new String(Base64Utils.encode(hash), "UTF-8").replaceAll("\r\n", ""); -      return hashBase64; - -    } catch (final Exception ex) { -      throw new EidasSAuthenticationException("internal.03", new Object[]{}, ex); - -    } +  private SimpleEidasData getEidData() { +    return SimpleEidasData.builder() +        .familyName("Mustermann") +        .givenName("Franz") +        .dateOfBirth("1989-05-05") +        .citizenCountryCode("IS") +        .pseudonym("1234sdgsdfg56789ABCDEF") +        .build();    } -  private PersonInfoType getPersonInfo() throws EidasSAuthenticationException { -    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); - -    // parse some eID attributes -    final Triple<String, String, String> eIdentifier = EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); -    final String uniqueId = createHashFromUniqueId(eIdentifier.getThird()); -    final String citizenCountry = eIdentifier.getFirst(); - -    // person information -    personName.setFamilyName(familyName); -    personName.setGivenName(givenName); -    naturalPerson.setDateOfBirth(dateOfBirth); -    eDocument.setIssuingCountry(citizenCountry); -    eDocument.setDocumentNumber(uniqueId); - -    // eID document information -    eDocument.setDocumentType(basicConfig -                                  .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, -                                                         Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); - -    return personInfo; -  }  } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/ZmrClientProductionTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/ZmrClientProductionTest.java new file mode 100644 index 00000000..5f3c5a55 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/ZmrClientProductionTest.java @@ -0,0 +1,43 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.clients; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.IfProfileValue; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.clients.zmr.ZmrSoapClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.clients.zmr.ZmrSoapClient.ZmrRegisterResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasSAuthenticationException; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; + +@IfProfileValue(name = "spring.profiles.active", value = "devEnvironment") +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_realConfig.xml"}) +@TestPropertySource(locations = { +    //"classpath:/application.properties", +    "file:/home/tlenz/Projekte/config/ms_connector/default_config.properties", +    }) +public class ZmrClientProductionTest { + +  @Autowired ZmrSoapClient client;   +  @Autowired IConfiguration basicConfig; +   +  @Test +  public void mdsSearch() throws EidasSAuthenticationException { +     +    ZmrRegisterResult result = client.searchWithMds(null,  +        "Thomas", "Lenz", "1982-09-06",  +        "AT"); +    +    assertNotNull("ZMR response", result); +     +  } +   +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/config/EidasConnectorMessageSourceTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/config/EidasConnectorMessageSourceTest.java new file mode 100644 index 00000000..1f96b25c --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/config/EidasConnectorMessageSourceTest.java @@ -0,0 +1,43 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.config; + +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import at.gv.egiz.eaaf.core.api.logging.IMessageSourceLocation; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml"}) +@DirtiesContext +public class EidasConnectorMessageSourceTest { + +  @Autowired +  private ResourceLoader loader; +  @Autowired(required = false) +  private List<IMessageSourceLocation> messageSources; + +  @Test +  public void checkMessageSources() { +    Assert.assertNotNull("No messageSource", messageSources); + +    for (final IMessageSourceLocation messageSource : messageSources) { +      Assert.assertNotNull("No sourcePath", messageSource.getMessageSourceLocation()); + +      for (final String el : messageSource.getMessageSourceLocation()) { +        final Resource messages = loader.getResource(el + ".properties"); +        Assert.assertTrue("Source not exist", messages.exists()); + +      } +    } +  } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyAuthConfigMap.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyAuthConfigMap.java new file mode 100644 index 00000000..ba531029 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyAuthConfigMap.java @@ -0,0 +1,144 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; +import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; + +import org.apache.commons.lang3.StringUtils; + +/** + * Dummy Application-configuration implementation for jUnit tests. + * + * @author tlenz + * + */ +public class DummyAuthConfigMap implements IConfigurationWithSP { + +  private Map<String, String> config = new HashMap<>(); + +  /** +   * Empty Dummy Application-configuration. +   * +   */ +  public DummyAuthConfigMap() { + +  } + +  /** +   * Dummy Application-configuration. +   * +   * @param configIs Property based configuration +   * @throws IOException In case of an configuration read error +   */ +  public DummyAuthConfigMap(final InputStream configIs) throws IOException { + +    final Properties props = new Properties(); +    props.load(configIs); + +    config = KeyValueUtils.convertPropertiesToMap(props); + +  } + +  /** +   * Dummy Application-configuration. +   * +   * @param path Path to property based configuration +   * @throws IOException In case of an configuration read error +   */ +  public DummyAuthConfigMap(final String path) throws IOException { + +    final Properties props = new Properties(); +    props.load(this.getClass().getResourceAsStream(path)); + +    config = KeyValueUtils.convertPropertiesToMap(props); + +  } + + +  @Override +  public String getBasicConfiguration(final String key) { +    return config.get(key); + +  } + +  @Override +  public String getBasicConfiguration(final String key, final String defaultValue) { +    final String value = getBasicConfiguration(key); +    if (StringUtils.isEmpty(value)) { +      return defaultValue; +    } else { +      return value; +    } + +  } + +  @Override +  public boolean getBasicConfigurationBoolean(final String key) { +    final String value = getBasicConfiguration(key); +    if (StringUtils.isEmpty(value)) { +      return false; +    } else { +      return Boolean.valueOf(value); +    } +  } + +  @Override +  public boolean getBasicConfigurationBoolean(final String key, final boolean defaultValue) { +    return Boolean.parseBoolean(getBasicConfiguration(key, String.valueOf(defaultValue))); + +  } + +  @Override +  public Map<String, String> getBasicConfigurationWithPrefix(final String prefix) { +    return KeyValueUtils.getSubSetWithPrefix(config, prefix); + +  } + +  @Override +  public ISpConfiguration getServiceProviderConfiguration(final String uniqueID) +      throws EaafConfigurationException { +    return null; +  } + +  @Override +  public <T> T getServiceProviderConfiguration(final String spIdentifier, final Class<T> decorator) +      throws EaafConfigurationException { +    return null; +  } + +  @Override +  public URI getConfigurationRootDirectory() { +    return new java.io.File(".").toURI(); + +  } + +  @Override +  public String validateIdpUrl(final URL authReqUrl) throws EaafException { +    return authReqUrl.toString(); +  } + +  public void putConfigValue(final String key, final String value) { +    config.put(key, value); +  } + +  public void removeConfigValue(final String key) { +    config.remove(key); + +  } + +  public void removeAll() { +    config.clear(); + +  } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyOA.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyOA.java new file mode 100644 index 00000000..074dd0bb --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyOA.java @@ -0,0 +1,304 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +import at.gv.egiz.eaaf.core.impl.builder.BpkBuilder; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; +import lombok.Getter; +import lombok.Setter; + +public class DummyOA implements IAhSpConfiguration { + +  private static final long serialVersionUID = 1L; +  private String uniqueAppId = null; +  private String targetIdentifier = null; +  private String friendlyName = null; +  private String cc = "AT"; +  private final Map<String, String> config = new HashMap<>(); +  private final List<Pair<String, String>> reqAttributes = new ArrayList<>(); + +  private boolean mandateEnabled = false; +  private boolean onlyMandateEnabled = false; +  private String mandateProfilesCsv; + +  private boolean eidasEnabled = false; + +  private boolean testCredentialEnabled = true; +  private String additionalBpkTargetCsv; +  private List<Pair<String, String>> additionalEncBpkTargets; + +  @Setter +  private boolean restricted = true; + +  @Setter +  private long latestVdaAuthentication = 60 * 365 * 5; + +  @Getter +  @Setter +  private boolean publicServiceProvider; + +  @Getter +  @Setter +  private boolean multiMandateEnabled; + +  @Setter +  private String bmiUniqueIdentifier; + +  @Override +  public Map<String, String> getFullConfiguration() { +    return this.config; +  } + +  @Override +  public String getConfigurationValue(final String key) { +    return this.config.get(key); +  } + +  @Override +  public String getConfigurationValue(final String key, final String defaultValue) { +    if (StringUtils.isNotEmpty(getConfigurationValue(key))) { +      return getConfigurationValue(key); +    } else { +      return defaultValue; +    } +  } + +  @Override +  public boolean isConfigurationValue(final String key) { +    if (StringUtils.isNotEmpty(getConfigurationValue(key))) { +      return Boolean.parseBoolean(getConfigurationValue(key)); +    } else { +      return false; +    } + +  } + +  @Override +  public boolean isConfigurationValue(final String key, final boolean defaultValue) { +    return Boolean.parseBoolean(getConfigurationValue(key, String.valueOf(defaultValue))); + +  } + +  @Override +  public boolean containsConfigurationKey(final String key) { +    return this.config.containsKey(key); +  } + +  @Override +  public String getUniqueIdentifier() { +    return this.uniqueAppId; +  } + +  @Override +  public String getUniqueApplicationRegisterIdentifier() { +    return this.bmiUniqueIdentifier; + +  } + +  @Override +  public String getFriendlyName() { +    return this.friendlyName; +  } + +  @Override +  public boolean hasBaseIdInternalProcessingRestriction() { +    // TODO Auto-generated method stub +    return false; +  } + +  @Override +  public boolean hasBaseIdTransferRestriction() { +    // TODO Auto-generated method stub +    return false; +  } + +  @Override +  public Set<String> getTargetsWithNoBaseIdInternalProcessingRestriction() { +    // TODO Auto-generated method stub +    return null; +  } + +  @Override +  public Set<String> getTargetsWithNoBaseIdTransferRestriction() { +    // TODO Auto-generated method stub +    return null; +  } + +  @Override +  public List<String> getRequiredLoA() { +    // TODO Auto-generated method stub +    return null; +  } + +  @Override +  public String getLoAMatchingMode() { +    // TODO Auto-generated method stub +    return null; +  } + +  @Override +  public String getAreaSpecificTargetIdentifier() { +    return this.targetIdentifier; +  } + +  @Override +  public boolean isTestCredentialEnabled() { +    return this.testCredentialEnabled; +  } + +  @Override +  public List<String> getTestCredentialOids() { +    // TODO Auto-generated method stub +    return null; +  } + +  @Override +  public List<Pair<String, String>> getRequiredAttributes() { +    return this.reqAttributes; + +  } + +  public void setUniqueAppId(final String uniqueAppId) { +    this.uniqueAppId = uniqueAppId; +  } + +  @Override +  public String getCountryCode() { +    return cc; +  } + +  @Override +  public void setCountryCode(final String cc) { +    this.cc = cc; + +  } + +  public void setTargetIdentifier(final String targetIdentifier) { +    this.targetIdentifier = BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(targetIdentifier); + +  } + +  public void setFriendlyName(final String friendlyName) { +    this.friendlyName = friendlyName; +  } + +  public void putGenericConfigurationKey(final String key, final String value) { +    this.config.put(key, value); + +  } + +  public void addRequiredAttribute(final String attrUri) { +    this.reqAttributes.add(Pair.newInstance(attrUri, null)); + +  } + +  public void removeRequiredAttribute(final String attrUri) { +    for (final Pair<String, String> el : reqAttributes) { +      if (el.getFirst().equals(attrUri)) { +        reqAttributes.remove(el); +        break; + +      } + + +    } +  } + +  public void addRequiredAttribute(final String attrUri, String param) { +    this.reqAttributes.add(Pair.newInstance(attrUri, param)); + +  } + +  @Override +  public boolean isMandateEnabled() { +    return this.mandateEnabled; +  } + +  @Override +  public boolean isOnlyMandateEnabled() { +    return this.onlyMandateEnabled; + +  } + +  @Override +  public List<String> getMandateProfiles() { +    return KeyValueUtils.getListOfCsvValues(mandateProfilesCsv); +  } + +  @Override +  public List<String> getAdditionalBpkTargets() { +    return KeyValueUtils.getListOfCsvValues(additionalBpkTargetCsv); + +  } + +  @Override +  public List<Pair<String, String>> getAdditionalForeignBpkTargets() { +    if (additionalEncBpkTargets == null) { +      return Collections.emptyList(); + +    } else { +      return additionalEncBpkTargets; + +    } +  } + +  @Override +  public long lastVdaAuthenticationDelay() { +    return latestVdaAuthentication; + +  } + +  @Override +  public boolean isRestrictedServiceProvider() { +    return this.restricted; +  } + + +  public void setMandateEnabled(final boolean mandateEnabled) { +    this.mandateEnabled = mandateEnabled; +  } + +  public void setOnlyMandateEnabled(final boolean onlyMandateEnabled) { +    this.onlyMandateEnabled = onlyMandateEnabled; +  } + +  public void setMandateProfilesCsv(final String mandateProfilesCsv) { +    this.mandateProfilesCsv = mandateProfilesCsv; +  } + +  public void setTestCredentialEnabled(final boolean testCredentialEnabled) { +    this.testCredentialEnabled = testCredentialEnabled; +  } + +  public void setAdditionalBpkTargetCsv(String additionalBpkTargetCsv) { +    this.additionalBpkTargetCsv = additionalBpkTargetCsv; +  } + +  public void setAdditionalEncBpkTargets(List<Pair<String, String>> additionalEncBpkTargets) { +    this.additionalEncBpkTargets = additionalEncBpkTargets; +  } + +  @Override +  public boolean isEnabled() { +    return true; +  } + +  @Override +  public boolean isEidasEnabled() { +    return this.eidasEnabled; + +  } + +  public void setEidasEnabled(boolean eidasEnabled) { +    this.eidasEnabled = eidasEnabled; +  } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyPendingRequest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyPendingRequest.java new file mode 100644 index 00000000..9a91ecbd --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyPendingRequest.java @@ -0,0 +1,8 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy; + +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; + +public class DummyPendingRequest extends RequestImpl { +  private static final long serialVersionUID = 8136280395622411505L; +} + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/IAhSpConfiguration.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/IAhSpConfiguration.java new file mode 100644 index 00000000..13d61f15 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/IAhSpConfiguration.java @@ -0,0 +1,152 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; +import at.gv.egiz.eaaf.core.impl.data.Pair; + +public interface IAhSpConfiguration extends ISpConfiguration { + + +  /** +   * Flag if this Service Provider is enabled. +   * +   * @return true if the SP is enabled, otherwise false +   */ +  boolean isEnabled(); + +  /** +   * Get unique identifier that is used in Application-Register from BM.I. +   * +   * <p>If no BM.I specific identifier is available then this method returns +   * the same identifier as <code>getUniqueIdentifier()</code></p> +   * +   * @return unique identifier from BM.I AppReg, or generic uniqueId of no specific exists +   */ +  String getUniqueApplicationRegisterIdentifier(); + +  /** +   * Flag that marks this Service-Provider as <i>public</i> or <i>private</i>. +   * +   * <p><b>Default:</b> If it is not set or has an unknown value, its <i>private</i> by default</p> +   * +   * @return <code>true</code> if it is from <i>public</i>, otherwise <code>false</code> +   */ +  boolean isPublicServiceProvider(); + +  /** +   * Enable test identities for this Service Provider. +   * +   * @return true if test identities are allowed, otherwise false +   */ +  boolean isTestCredentialEnabled(); + +  /** +   * Get a List of OID's that refine the set of allowed test identities. +   * +   * @return @link {@link List} of test-identity OID's +   */ +  @Nullable +  List<String> getTestCredentialOids(); + + +  /** +   * Get a List of unique attribute URI's that are required by this SP. +   * +   * @return {@link List} of attribute URI's / parameter {@link Pair}s +   */ +  List<Pair<String, String>> getRequiredAttributes(); + + +  /** +   * Get the CountryCode for this service. <br> +   * <br> +   * <b>Default:</b> AT +   * +   * @return +   */ +  String getCountryCode(); + +  /** +   * Set the CountryCode for this service. If not countryCode is set, AT is used as default. +   * +   * @param cc Service-Provider country-code +   */ +  void setCountryCode(String cc); + +  /** +   * Enable mandates for this service provider. +   * +   * @return <code>true</code> if mandates are enabled, otherwise <code>false</code> +   */ +  boolean isMandateEnabled(); + +  /** +   * Enables multi-mandates for this service-provider. +   * +   * @return <code>true</code> if multi-mandates are enabled, otherwise <code>false</code> +   */ +  boolean isMultiMandateEnabled(); + +  /** +   * Only mandates are allowed for this service provider. +   * +   * @return <code>true</code> if only mandates are allowed, otherwise <code>false</code> +   */ +  boolean isOnlyMandateEnabled(); + +  /** +   * Get a {@link List} of mandate profiles that are supported by this Service provider. +   * +   * @return +   */ +  @Nonnull List<String> getMandateProfiles(); + + +  /** +   * eIDAS authentication allowed flag. +   * +   * @return <code>true</code> if eIDAS authentication is enabled, otherwise <code>false</code> +   */ +  boolean isEidasEnabled(); + +  /** +   * Get a List of targets for additional bPKs that are required by this service provider. +   * +   * @return List of prefixed bPK targets +   */ +  @Nonnull List<String> getAdditionalBpkTargets(); + +  /** +   * Get a list of foreign bPK targets that are required by this service provider. +   * +   * @return List of pairs with prefixed bPK targets as first element and VKZ as second element +   */ +  @Nonnull List<Pair<String, String>> getAdditionalForeignBpkTargets(); + +  /** +   * Flag that indicates that service-provider as restricted or unrestricted. +   * +   * <p>A restricted service-provider can only used by test-identities that contains a +   * valid application-restriction in User-Certificate Pinning</p> +   * +   * <p><b>Default:</b> true</p> +   * +   * @return <code>true</code> if it is restricted, otherwise <code>false</code> +   */ +  boolean isRestrictedServiceProvider(); + + +/** + * Defines the time in minutes how long the last VDA registration h@Override + ave passed as maximum. + * + * @return time in minutes + */ +long lastVdaAuthenticationDelay(); + +} + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/DeSpecificDetailSearchProcessorTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/DeSpecificDetailSearchProcessorTest.java new file mode 100644 index 00000000..21c9fd80 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/DeSpecificDetailSearchProcessorTest.java @@ -0,0 +1,105 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.BlockJUnit4ClassRunner; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; +import at.gv.bmi.namespace.zmr_su.zmr._20040201.PersonSuchenRequest; + +@RunWith(BlockJUnit4ClassRunner.class) +public class DeSpecificDetailSearchProcessorTest { + +  private DeSpecificDetailSearchProcessor handler = new DeSpecificDetailSearchProcessor(); +   +  @Test +  public void checkName() {     +    assertEquals("wrong handler name", "DeSpecificDetailSearchProcessor", handler.getName()); +     +  } +   +  @Test +  public void canHandlerCheck_1() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .birthName(RandomStringUtils.randomAlphabetic(5)) +        .placeOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .build();     +    assertFalse("wrong 'canHandle' flag", handler.canHandle("XX", eidData)); +     +  } +   +  @Test +  public void canHandlerCheck_2() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .birthName(RandomStringUtils.randomAlphabetic(5)) +        .placeOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .build();     +    assertTrue("wrong 'canHandle' flag", handler.canHandle("DE", eidData)); +     +  } +   +  @Test +  public void canHandlerCheck_3() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .birthName(RandomStringUtils.randomAlphabetic(5)) +        .placeOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .build();     +    assertTrue("wrong 'canHandle' flag", handler.canHandle("de", eidData)); +     +  } +   +  @Test +  public void canHandlerCheck_4() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .birthName(null) +        .placeOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .build();     +    assertFalse("wrong 'canHandle' flag", handler.canHandle("DE", eidData)); +     +  } +   +  @Test +  public void canHandlerCheck_5() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .birthName(RandomStringUtils.randomAlphabetic(5)) +        .placeOfBirth(null) +        .build();     +    assertFalse("wrong 'canHandle' flag", handler.canHandle("DE", eidData)); +     +  } + +  @Test +  public void generateZmrSearchRequest() { +    SimpleEidasData eidData = SimpleEidasData.builder() +        .citizenCountryCode("DE") +        .givenName(RandomStringUtils.randomAlphabetic(5)) +        .familyName(RandomStringUtils.randomAlphabetic(5)) +        .dateOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .birthName(RandomStringUtils.randomAlphabetic(5)) +        .placeOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .build(); +     +    // perform operation +    PersonSuchenRequest req = handler.generateSearchRequest(eidData); +     +    //validate response +    assertNotNull("no search request", req); +    assertNotNull("no MDS", req.getNatuerlichePerson()); +    assertNotNull("no MDS PersonName", req.getNatuerlichePerson().getPersonenName()); +    assertEquals("familyName", eidData.getFamilyName(), req.getNatuerlichePerson().getPersonenName().getFamilienname()); +    assertEquals("givenName", eidData.getGivenName(), req.getNatuerlichePerson().getPersonenName().getVorname()); +    assertEquals("birthday", eidData.getDateOfBirth(), req.getNatuerlichePerson().getGeburtsdatum()); +         +    assertNotNull("no eIDAS documenst", req.getEidasSuchdaten()); +    //TODO: add validation if we can add more than one eIDAS document  +           +  } +   +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/ItSpecificDetailSearchProcessorTes.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/ItSpecificDetailSearchProcessorTes.java new file mode 100644 index 00000000..9b638ee5 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/ItSpecificDetailSearchProcessorTes.java @@ -0,0 +1,84 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.BlockJUnit4ClassRunner; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; +import at.gv.bmi.namespace.zmr_su.zmr._20040201.PersonSuchenRequest; + +@RunWith(BlockJUnit4ClassRunner.class) +public class ItSpecificDetailSearchProcessorTes { + +  private ItSpecificDetailSearchProcessor handler = new ItSpecificDetailSearchProcessor(); +   +  @Test +  public void checkName() {     +    assertEquals("wrong handler name", "ItSpecificDetailSearchProcessor", handler.getName()); +     +  } +   +  @Test +  public void canHandlerCheck_1() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .taxNumber(RandomStringUtils.randomAlphabetic(5)) +        .build();     +    assertFalse("wrong 'canHandle' flag", handler.canHandle("XX", eidData)); +     +  } +   +  @Test +  public void canHandlerCheck_2() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .taxNumber(RandomStringUtils.randomAlphabetic(5)) +        .build();     +    assertTrue("wrong 'canHandle' flag", handler.canHandle("IT", eidData)); +     +  } +   +  @Test +  public void canHandlerCheck_3() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .taxNumber(RandomStringUtils.randomAlphabetic(5)) +        .build();     +    assertTrue("wrong 'canHandle' flag", handler.canHandle("it", eidData)); +     +  } +   +  @Test +  public void canHandlerCheck_4() {     +    SimpleEidasData eidData = SimpleEidasData.builder() +        .taxNumber("") +        .build();     +    assertFalse("wrong 'canHandle' flag", handler.canHandle("IT", eidData)); +     +  } +   +  @Test +  public void generateZmrSearchRequest() { +    SimpleEidasData eidData = SimpleEidasData.builder() +        .citizenCountryCode("IT") +        .givenName(RandomStringUtils.randomAlphabetic(5)) +        .familyName(RandomStringUtils.randomAlphabetic(5)) +        .dateOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .taxNumber(RandomStringUtils.randomAlphabetic(5)) +        .build(); +     +    // perform operation +    PersonSuchenRequest req = handler.generateSearchRequest(eidData); +     +    //validate response +    assertNotNull("no search request", req); + +    //TODO: add validation if we can add more information about taxNumber from Italy  +           +  } +   +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaAuthSignalControllerTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaAuthSignalControllerTest.java new file mode 100644 index 00000000..cddcd11c --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaAuthSignalControllerTest.java @@ -0,0 +1,197 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +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.util.SerializationUtils; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.controller.IdAustriaClientAuthSignalController; +import at.gv.egiz.eaaf.core.api.IRequestStorage; +import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; +import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummyProtocolAuthService; +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.spring.test.DummyTransactionStorage.DummyDbEntry; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +public class IdAustriaAuthSignalControllerTest { + +  @Autowired(required = true) +  private IdAustriaClientAuthSignalController controller; +  @Autowired(required = true) +  private ITransactionStorage cache; +  @Autowired(required = true) +  private IPendingRequestIdGenerationStrategy pendingReqGeneration; +  @Autowired(required = true) +  private IRequestStorage reqStorage; +  @Autowired(required = true) +  private IConfiguration basicConfig; +  @Autowired private ITransactionStorage transactionStorage; +   +  @Autowired private DummyProtocolAuthService protAuthService; + +  @Test +  public void noRelayState() throws IOException, EaafException { +    final MockHttpServletRequest httpReq = +        new MockHttpServletRequest("POST", "https://localhost/authhandler"); +    final MockHttpServletResponse httpResp = new MockHttpServletResponse(); + +    controller.performAuthentication(httpReq, httpResp); +    Assert.assertEquals("httpStausCode", 200, httpResp.getStatus()); + +    final String errorId = protAuthService.getErrorKey(); +    final Object error = cache.get(errorId); +    Assert.assertNotNull("Error is null", error); +    org.springframework.util.Assert.isInstanceOf(byte[].class, +        ((DummyDbEntry) error).getObj()); +    final Object errorObj = SerializationUtils.deserialize((byte[]) ((DummyDbEntry) error).getObj()); +    org.springframework.util.Assert.isInstanceOf(ExceptionContainer.class, errorObj); +    org.springframework.util.Assert.isInstanceOf(EaafException.class, +        ((ExceptionContainer) errorObj).getExceptionThrown()); + +  } + +  @Test +  public void validRelayStateNoPendingReqId() throws EaafException, IOException { +    final String pendingReqId = pendingReqGeneration.generateExternalPendingRequestId(); +    final MockHttpServletRequest httpReq = +        new MockHttpServletRequest("POST", "https://localhost/authhandler"); +    httpReq.addParameter(IdAustriaClientAuthSignalController.HTTP_PARAM_RELAYSTATE, pendingReqId); +    final MockHttpServletResponse httpResp = new MockHttpServletResponse(); + +    controller.performAuthentication(httpReq, httpResp); +    Assert.assertEquals("httpStausCode", 200, httpResp.getStatus()); + +    final String errorId = protAuthService.getErrorKey(); +    final Object error = cache.get(errorId); +    Assert.assertNotNull("Error is null", error); +    org.springframework.util.Assert.isInstanceOf(byte[].class, +        ((DummyDbEntry) error).getObj()); +    final Object errorObj = SerializationUtils.deserialize((byte[]) ((DummyDbEntry) error).getObj()); +    org.springframework.util.Assert.isInstanceOf(ExceptionContainer.class, errorObj); +    org.springframework.util.Assert.isInstanceOf(EaafException.class, +        ((ExceptionContainer) errorObj).getExceptionThrown()); +    //TODO: +    Assert.assertEquals("ErrorCode not match", "auth.26", +        ((EaafException) ((ExceptionContainer) errorObj).getExceptionThrown()).getErrorId()); + +  } + +  @Test +  public void validRelayStateSuspectPendingReqId() throws EaafException, IOException { +    String relayState = RandomStringUtils.randomAlphanumeric(10);     +    transactionStorage.put(relayState, false, -1); +     +    final MockHttpServletRequest httpReq = +        new MockHttpServletRequest("POST", "https://localhost/authhandler"); +    httpReq.addParameter(IdAustriaClientAuthSignalController.HTTP_PARAM_RELAYSTATE, relayState); +    final MockHttpServletResponse httpResp = new MockHttpServletResponse(); + +    controller.performAuthentication(httpReq, httpResp); +    Assert.assertEquals("httpStausCode", 200, httpResp.getStatus()); + +    final String errorId = protAuthService.getErrorKey(); +    final Object error = cache.get(errorId); +    Assert.assertNotNull("Error is null", error); +    org.springframework.util.Assert.isInstanceOf(byte[].class, +        ((DummyDbEntry) error).getObj()); +    final Object errorObj = SerializationUtils.deserialize((byte[]) ((DummyDbEntry) error).getObj()); +    org.springframework.util.Assert.isInstanceOf(ExceptionContainer.class, errorObj); +    org.springframework.util.Assert.isInstanceOf(EaafException.class, +        ((ExceptionContainer) errorObj).getExceptionThrown()); +    //TODO: +    Assert.assertEquals("ErrorCode not match", "auth.26", +        ((EaafException) ((ExceptionContainer) errorObj).getExceptionThrown()).getErrorId()); +     +    Assert.assertNull("RelayState was not removed", transactionStorage.get(relayState)); + +  } +   +  @Test +  public void validRelayStateNoPendingReq() throws EaafException, IOException { +    final String pendingReqId = pendingReqGeneration.generateExternalPendingRequestId(); +    String relayState = RandomStringUtils.randomAlphanumeric(10);     +    transactionStorage.put(relayState, pendingReqId, -1); +     +    final MockHttpServletRequest httpReq = +        new MockHttpServletRequest("POST", "https://localhost/authhandler"); +    httpReq.addParameter(IdAustriaClientAuthSignalController.HTTP_PARAM_RELAYSTATE, relayState); +    final MockHttpServletResponse httpResp = new MockHttpServletResponse(); + +    controller.performAuthentication(httpReq, httpResp); +    Assert.assertEquals("httpStausCode", 200, httpResp.getStatus()); + +    final String errorId = protAuthService.getErrorKey(); +    final Object error = cache.get(errorId); +    Assert.assertNotNull("Error is null", error); +    org.springframework.util.Assert.isInstanceOf(byte[].class, +        ((DummyDbEntry) error).getObj()); +    final Object errorObj = SerializationUtils.deserialize((byte[]) ((DummyDbEntry) error).getObj()); +    org.springframework.util.Assert.isInstanceOf(ExceptionContainer.class, errorObj); +    org.springframework.util.Assert.isInstanceOf(EaafException.class, +        ((ExceptionContainer) errorObj).getExceptionThrown()); +    Assert.assertEquals("ErrorCode not match", "auth.28", +        ((EaafException) ((ExceptionContainer) errorObj).getExceptionThrown()).getErrorId()); + +    Assert.assertNull("RelayState was not removed", transactionStorage.get(relayState)); +     +  } +   +  @Test +  public void validRelayStateWithPendingReq() throws EaafException, IOException { +    final String pendingReqId = pendingReqGeneration.generateExternalPendingRequestId(); + +    String relayState = RandomStringUtils.randomAlphanumeric(10);     +    transactionStorage.put(relayState, pendingReqId, -1); +     +    final TestRequestImpl pendingReq = new TestRequestImpl(); +    pendingReq.setPendingReqId(pendingReqId); +    pendingReq.setAuthUrl("http://localhost/idp"); +    final Map<String, String> spConfigMap = new HashMap<>(); +    spConfigMap.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "http://test.sp"); +    final DummySpConfiguration spConfig = new DummySpConfiguration(spConfigMap, basicConfig); +    pendingReq.setSpConfig(spConfig); +    reqStorage.storePendingRequest(pendingReq); + +    final MockHttpServletRequest httpReq = +        new MockHttpServletRequest("POST", "https://localhost/authhandler"); +    httpReq.addParameter(IdAustriaClientAuthSignalController.HTTP_PARAM_RELAYSTATE, relayState); +    final MockHttpServletResponse httpResp = new MockHttpServletResponse(); + +    controller.performAuthentication(httpReq, httpResp); + +    Assert.assertEquals("httpStausCode", 200, httpResp.getStatus()); + +    final String errorId = protAuthService.getErrorKey(); +    final Object error = cache.get(errorId); +    Assert.assertNotNull("Error is null", error); +    org.springframework.util.Assert.isInstanceOf(byte[].class, +        ((DummyDbEntry) error).getObj()); +    final Object errorObj = SerializationUtils.deserialize((byte[]) ((DummyDbEntry) error).getObj()); +    org.springframework.util.Assert.isInstanceOf(ExceptionContainer.class, errorObj); +    org.springframework.util.Assert.isInstanceOf(EaafException.class, +        ((ExceptionContainer) errorObj).getExceptionThrown()); +    Assert.assertEquals("ErrorCode not match", +        "PendingRequest object is not of type 'RequestImpl.class'", +        ((EaafException) ((ExceptionContainer) errorObj).getExceptionThrown()).getErrorId()); +  } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthHealthCheckTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthHealthCheckTest.java new file mode 100644 index 00000000..a583ab2a --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthHealthCheckTest.java @@ -0,0 +1,128 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; + +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.io.UnmarshallingException; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.saml2.metadata.EntityDescriptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.health.Health; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.w3c.dom.Element; + +import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthHealthCheck; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.utils.IPvp2CredentialProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import net.shibboleth.utilities.java.support.resolver.ResolverException; +import net.shibboleth.utilities.java.support.xml.SerializeSupport; +import net.shibboleth.utilities.java.support.xml.XMLParserException; +import okhttp3.HttpUrl; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +public class IdAustriaClientAuthHealthCheckTest { + +  @Autowired private IdAustriaClientAuthHealthCheck toCheck; +  @Autowired protected MsConnectorDummyConfigMap config; +  @Autowired private IPvp2CredentialProvider credentialProvider; +  @Autowired IdAustriaClientAuthMetadataProvider provider; +   +  private static MockWebServer mockWebServer; +  private static HttpUrl mockServerUrl; +   +  /** +   * JUnit class initializer. +   * +   * @throws Exception In case of an OpenSAML3 initialization error +   */ +  @BeforeClass +  public static void classInitializer() throws Exception { +    EaafOpenSaml3xInitializer.eaafInitialize(); + +    mockWebServer = new MockWebServer(); +    mockServerUrl = mockWebServer.url("/sp/metadata"); + +  } +  +  @Test +  public void notActive() { +    //set-up test +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID,  +        null); +     +    //perform check +    Health status = toCheck.health(); +     +    //evaluate status +    Assert.assertEquals("wrong status", Health.unknown().build().getStatus(), status.getStatus()); +     +  } +   +  @Test +  public void success() throws SamlSigningException, CredentialsNotAvailableException,  +      XMLParserException, UnmarshallingException, MarshallingException { + +    //set-up test +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID,  +        mockServerUrl.url().toString()); +    injectValidHttpMetadata(mockServerUrl.url().toString()); +     +    //perform check +    Health status = toCheck.health(); +     +    //evaluate status +    Assert.assertEquals("wrong status", Health.up().build().getStatus(), status.getStatus()); +         +  } +   +  @Test +  public void invalid() throws SamlSigningException, CredentialsNotAvailableException,  +      XMLParserException, UnmarshallingException, MarshallingException, ResolverException { +    //set-up test +    provider.clear(); +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID,  +        "http://localhost:1234/junit/metadata"); +         +    //perform check +    Health status = toCheck.health(); +     +    //evaluate status +    Assert.assertEquals("wrong status", Health.outOfService().build().getStatus(), status.getStatus()); +     +  } +   +  private String injectValidHttpMetadata(String dynEntityId) throws XMLParserException, +      UnmarshallingException, MarshallingException, SamlSigningException, CredentialsNotAvailableException { +    final EntityDescriptor metadata = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream( +    XMLObjectProviderRegistrySupport.getParserPool(), +    IdAustriaClientAuthHealthCheckTest.class.getResourceAsStream("/data/idp_metadata_no_sig.xml")); +    metadata.setValidUntil(DateTime.now().plusDays(1)); +    metadata.setSignature(null); +    metadata.setEntityID(dynEntityId); +    Saml2Utils.signSamlObject(metadata, credentialProvider.getMetaDataSigningCredential(), true); +    final Element metadataElement = XMLObjectSupport.marshall(metadata); +    mockWebServer.enqueue(new MockResponse().setResponseCode(200) +        .setBody(SerializeSupport.nodeToString(metadataElement)) +        .setHeader("Content-Type", "text/html;charset=utf-8")); +    return dynEntityId; + +} +   +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataControllerTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataControllerTest.java new file mode 100644 index 00000000..4671684f --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataControllerTest.java @@ -0,0 +1,133 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.UnmarshallingException; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.common.xml.SAMLConstants; +import org.opensaml.saml.metadata.resolver.filter.FilterException; +import org.opensaml.saml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml.saml2.metadata.SPSSODescriptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.controller.IdAustriaClientAuthMetadataController; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.SchemaValidationFilter; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.SimpleMetadataSignatureVerificationFilter; +import net.shibboleth.utilities.java.support.xml.XMLParserException; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class IdAustriaClientAuthMetadataControllerTest { + +  private MockHttpServletRequest httpReq; +  private MockHttpServletResponse httpResp; + +  @Autowired private IdAustriaClientAuthMetadataController controller; +  @Autowired private IdAustriaClientAuthCredentialProvider credProvider; + +  /** +   * JUnit class initializer. +   * +   * @throws Exception In case of an OpenSAML3 initialization error +   */ +  @BeforeClass +  public static void initialize() throws Exception { +    EaafOpenSaml3xInitializer.eaafInitialize(); + +  } + +  /** +   * Single jUnit-test set-up. +   */ +  @Before +  public void testSetup() { +    httpReq = new MockHttpServletRequest("GET", "http://localhost/authhandler"); +    httpReq.setContextPath("/authhandler"); +    httpResp = new MockHttpServletResponse(); + +  } + +  @Test +  public void buildMetadataValidInEidMode() throws IOException, EaafException, +      XMLParserException, UnmarshallingException, FilterException { + +    //build metdata +    controller.getSpMetadata(httpReq, httpResp); + +    //check result +    validateResponse(7); + +  } + +  private void validateResponse(int numberOfRequestedAttributes) throws UnsupportedEncodingException, +      XMLParserException, UnmarshallingException, FilterException, CredentialsNotAvailableException { +    Assert.assertEquals("HTTP Statuscode", 200, httpResp.getStatus()); +    Assert.assertEquals("ContentType", "text/xml; charset=utf-8", httpResp.getContentType()); +    Assert.assertEquals("ContentEncoding", "UTF-8", httpResp.getCharacterEncoding()); + +    final String metadataXml = httpResp.getContentAsString(); +    Assert.assertNotNull("XML Metadata", metadataXml); + +    final EntityDescriptor metadata = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream( +        XMLObjectProviderRegistrySupport.getParserPool(), new ByteArrayInputStream(metadataXml.getBytes("UTF-8"))); + +    Assert.assertEquals("EntityId", +        "http://localhost/authhandler" + IdAustriaClientAuthConstants.ENDPOINT_METADATA, +        metadata.getEntityID()); + +    //check XML scheme +    final SchemaValidationFilter schemaFilter = new SchemaValidationFilter(); +    schemaFilter.filter(metadata); + +    //check signature +    final SimpleMetadataSignatureVerificationFilter sigFilter = +        new SimpleMetadataSignatureVerificationFilter(credProvider.getKeyStore().getFirst(), +            metadata.getEntityID()); +    sigFilter.filter(metadata); + +    //check content +    final SPSSODescriptor spSsoDesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); +    Assert.assertNotNull("SPSSODescr.", spSsoDesc); + +    Assert.assertFalse("AssertionConsumerServices", +        spSsoDesc.getAssertionConsumerServices().isEmpty()); + +    Assert.assertFalse("KeyDescriptors", +        spSsoDesc.getKeyDescriptors().isEmpty()); +    Assert.assertEquals("#KeyDescriptors", 2, spSsoDesc.getKeyDescriptors().size()); + +    Assert.assertFalse("NameIDFormats", +        spSsoDesc.getNameIDFormats().isEmpty()); +    Assert.assertEquals("wrong NameIDFormats", "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", +        spSsoDesc.getNameIDFormats().get(0).getFormat()); + +    Assert.assertFalse("AttributeConsumingServices", +        spSsoDesc.getAttributeConsumingServices().isEmpty()); +    Assert.assertEquals("#RequestAttributes", numberOfRequestedAttributes, +        spSsoDesc.getAttributeConsumingServices().get(0).getRequestAttributes().size()); + +  } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderFirstTest.java new file mode 100644 index 00000000..da10fc54 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderFirstTest.java @@ -0,0 +1,238 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; + +import java.io.IOException; + +import org.apache.commons.lang3.RandomStringUtils; +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.criterion.EntityIdCriterion; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.io.UnmarshallingException; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.saml2.metadata.EntityDescriptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.w3c.dom.Element; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.utils.IPvp2CredentialProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.test.metadata.MetadataResolverTest; +import net.shibboleth.utilities.java.support.resolver.CriteriaSet; +import net.shibboleth.utilities.java.support.resolver.ResolverException; +import net.shibboleth.utilities.java.support.xml.SerializeSupport; +import net.shibboleth.utilities.java.support.xml.XMLParserException; +import okhttp3.HttpUrl; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +public class IdAustriaClientAuthMetadataProviderFirstTest { + +  @Autowired +  IPvp2CredentialProvider credentialProvider; +  @Autowired +  IdAustriaClientAuthMetadataProvider provider; +  @Autowired +  PvpMetadataResolverFactory resolverFactory; + +  private static MockWebServer mockWebServer; +  private static HttpUrl mockServerUrl; + +  /** +   * JUnit class initializer. +   * +   * @throws Exception In case of an OpenSAML3 initialization error +   */ +  @BeforeClass +  public static void classInitializer() throws Exception { +    EaafOpenSaml3xInitializer.eaafInitialize(); + +    mockWebServer = new MockWebServer(); +    mockServerUrl = mockWebServer.url("/sp/metadata"); + +  } + +  /** +   * jUnit test set-up. +   *  +   * @throws ResolverException +   * +   */ +  @Before +  public void testSetup() { +    provider.fullyDestroy(); + +  } + +  @Test +  public void simpleManuelAddingTest() throws Pvp2MetadataException, ResolverException { +    final IPvp2MetadataProvider resolver1 = resolverFactory.createMetadataProvider( +        "classpath:/data/idp_metadata_sig_notvalid.xml", +        null, "junit", null); +    Assert.assertNotNull("Resolver 1 is null", resolver1); +    provider.addMetadataResolverIntoChain(resolver1); + +    final IPvp2MetadataProvider resolver2 = resolverFactory.createMetadataProvider( +        "classpath:/data/idp_metadata_sig_valid_wrong_alg.xml", +        null, "junit", null); +    Assert.assertNotNull("Resolver 2 is null", resolver2); +    provider.addMetadataResolverIntoChain(resolver2); + +    final EntityDescriptor entity1 = provider.getEntityDescriptor("https://localEntity"); +    Assert.assertNotNull("Entity 1 not found", entity1); + +    final EntityDescriptor entity2 = provider.getEntityDescriptor( +        "https://vidp.gv.at/ms_connector/pvp/metadata"); +    Assert.assertNotNull("Entity 2 not found", entity2); + +    final EntityDescriptor entity3 = provider.getEntityDescriptor("https://egiz.gv.at/abababa"); +    Assert.assertNull("Entity 3 found", entity3); + +  } + +  @Test +  public void dynamicLoadingNoValidSignature() throws ResolverException { +    final EntityDescriptor entity = provider.getEntityDescriptor("classpath:/data/idp_metadata_no_sig2.xml"); +    Assert.assertNull("Entity found", entity); + +  } + +  @Test +  public void dynamicLoadingValidSignature() throws XMLParserException, UnmarshallingException, +      SamlSigningException, CredentialsNotAvailableException, MarshallingException, ResolverException { + +    final String entityId = injectValidHttpMetadata(); +    final EntityDescriptor entity = provider.getEntityDescriptor(entityId); +    Assert.assertNotNull("Entity not found", entity); + +  } + +  @Test +  public void reloadNotPossible() throws XMLParserException, UnmarshallingException, +      SamlSigningException, CredentialsNotAvailableException, MarshallingException, ResolverException { + +    final String entityId = injectValidHttpMetadata(); +    final EntityDescriptor entity = provider.getEntityDescriptor(entityId); +    Assert.assertNotNull("Entity not found", entity); +    Assert.assertNotNull("Entity not found", +        provider.resolveSingle(generateEntityIdCreteria(entityId))); + +    Assert.assertFalse("Refresh should not be possible", +        provider.refreshMetadataProvider(entityId)); + +    final EntityDescriptor entity2 = provider.getEntityDescriptor(entityId); +    Assert.assertNull("Entity not found", entity2); +    Assert.assertNull("Entity not found", +        provider.resolveSingle(generateEntityIdCreteria(entityId))); + +    Assert.assertFalse("Last refresh", provider.wasLastRefreshSuccess()); + +  } + +  @Test +  public void refeshTest() throws Pvp2MetadataException, ResolverException { +    Assert.assertFalse("Last refresh", provider.wasLastRefreshSuccess()); +    Assert.assertNull("LastRefresh", provider.getLastRefresh()); +    Assert.assertNull("LastSuccessfulRefresh", provider.getLastSuccessfulRefresh()); +    Assert.assertNull("LastUpdate", provider.getLastUpdate()); + +    final IPvp2MetadataProvider resolver1 = resolverFactory.createMetadataProvider( +        "classpath:/data/idp_metadata_sig_notvalid.xml", +        null, "junit", null); +    Assert.assertNotNull("Resolver 1 is null", resolver1); +    provider.addMetadataResolverIntoChain(resolver1); + +    final IPvp2MetadataProvider resolver2 = resolverFactory.createMetadataProvider( +        "classpath:/data/idp_metadata_sig_valid_wrong_alg.xml", +        null, "junit", null); +    Assert.assertNotNull("Resolver 2 is null", resolver2); +    provider.addMetadataResolverIntoChain(resolver2); + +    provider.refresh(); + +    Assert.assertTrue("Last refresh", provider.wasLastRefreshSuccess()); +    Assert.assertNotNull("LastRefresh", provider.getLastRefresh()); +    Assert.assertNotNull("LastSuccessfulRefresh", provider.getLastSuccessfulRefresh()); +    Assert.assertNotNull("LastUpdate", provider.getLastUpdate()); + +  } + +  @Test +  public void reloadPossible() throws XMLParserException, UnmarshallingException, +      SamlSigningException, CredentialsNotAvailableException, MarshallingException, ResolverException, +      IOException { + +    mockWebServer.shutdown(); +    mockWebServer = new MockWebServer(); +    mockServerUrl = mockWebServer.url("/sp/metadata"); + +    final String entityId = injectValidHttpMetadata(); +    final EntityDescriptor entity = provider.getEntityDescriptor(entityId); +    Assert.assertNotNull("Entity not found", entity); +    Assert.assertNotNull("Entity not found", +        provider.resolveSingle(generateEntityIdCreteria(entityId))); + +    Assert.assertFalse("Last refresh", provider.wasLastRefreshSuccess()); + +    injectValidHttpMetadata(entityId); +    Assert.assertTrue("Refresh should not be possible", +        provider.refreshMetadataProvider(entityId)); + +    final EntityDescriptor entity2 = provider.getEntityDescriptor(entityId); +    Assert.assertNotNull("Entity not found", entity2); +    Assert.assertNotNull("Entity not found", +        provider.resolveSingle(generateEntityIdCreteria(entityId))); + +    Assert.assertFalse("Last refresh", provider.wasLastRefreshSuccess()); + +  } + +  private String injectValidHttpMetadata() throws SamlSigningException, CredentialsNotAvailableException, +      XMLParserException, UnmarshallingException, MarshallingException { +    return injectValidHttpMetadata(mockServerUrl.url().toString() +        + "/" + RandomStringUtils.randomAlphabetic(5)); +  } + +  private String injectValidHttpMetadata(String dynEntityId) throws XMLParserException, +      UnmarshallingException, +      MarshallingException, SamlSigningException, CredentialsNotAvailableException { +    final EntityDescriptor metadata = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream( +        XMLObjectProviderRegistrySupport.getParserPool(), +        MetadataResolverTest.class.getResourceAsStream("/data/idp_metadata_no_sig.xml")); +    metadata.setValidUntil(DateTime.now().plusDays(1)); +    metadata.setSignature(null); +    metadata.setEntityID(dynEntityId); +    Saml2Utils.signSamlObject(metadata, credentialProvider.getMetaDataSigningCredential(), true); +    final Element metadataElement = XMLObjectSupport.marshall(metadata); +    mockWebServer.enqueue(new MockResponse().setResponseCode(200) +        .setBody(SerializeSupport.nodeToString(metadataElement)) +        .setHeader("Content-Type", "text/html;charset=utf-8")); + +    return dynEntityId; + +  } + +  private CriteriaSet generateEntityIdCreteria(String entityId) { +    final CriteriaSet result = new CriteriaSet(); +    result.add(new EntityIdCriterion(entityId)); +    return result; + +  } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderSecondTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderSecondTest.java new file mode 100644 index 00000000..3ee6ddcd --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderSecondTest.java @@ -0,0 +1,66 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.saml.saml2.metadata.EntityDescriptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import net.shibboleth.utilities.java.support.resolver.ResolverException; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +public class IdAustriaClientAuthMetadataProviderSecondTest { + +  @Autowired +  IdAustriaClientAuthMetadataProvider provider; + +  /** +   * JUnit class initializer. +   * +   * @throws Exception In case of an OpenSAML3 initialization error +   */ +  @BeforeClass +  public static void classInitializer() throws Exception { +    EaafOpenSaml3xInitializer.eaafInitialize(); + +  } + +  /** +   * jUnit test set-up. +   * +   * @throws ResolverException +   * +   */ +  @Before +  public void testSetup() { +    provider.fullyDestroy(); + +  } + +  @Test +  public void notTrustedX509CertsInTrustStore() throws ResolverException { +    final EntityDescriptor entity = provider.getEntityDescriptor("classpath:/data/idp_metadata_no_sig2.xml"); +    Assert.assertNull("Entity found", entity); + +  } + +  @Test +  public void readStaticInfos() { +    Assert.assertEquals("wrong providerId", +        IdAustriaClientAuthMetadataProvider.PROVIDER_ID, provider.getId()); + +    provider.runGarbageCollector(); + +  } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientCredentialProviderTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientCredentialProviderTest.java new file mode 100644 index 00000000..3e37e1a6 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientCredentialProviderTest.java @@ -0,0 +1,414 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.common.base.Optional; +import com.google.common.base.Predicates; +import com.google.common.base.Throwables; +import com.google.common.collect.FluentIterable; + +import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; +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.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafFactoryException; +import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_basic_lazy.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +@DirtiesContext +public class IdAustriaClientCredentialProviderTest { + +  private static final String PATH_JKS = "../keystore/junit_test.jks"; +  private static final String ALIAS_METADATA = "meta"; +  private static final String ALIAS_SIGN = "sig"; +  private static final String ALIAS_ENC = "enc"; +  private static final String PASSWORD = "password"; + +  @Autowired +  private ApplicationContext context; +  @Autowired(required = true) +  protected MsConnectorDummyConfigMap config; + +  /** +   * jUnit test initializer. +   */ +  @Before +  public void initialize() { +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_KEYSTORE_PATH, PATH_JKS); +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_KEYSTORE_PASSWORD, PASSWORD); + +    config.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_ALIAS); +    config.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_KEY_PASSWORD); + +    config.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS); +    config.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_KEY_PASSWORD); + +    config.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_ALIAS); +    config.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_KEY_PASSWORD); + +  } + +  @Test +  @DirtiesContext +  public void noKeyStoreUrl() { +    config.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_KEYSTORE_PATH); +    try { +      context.getBean(IdAustriaClientAuthCredentialProvider.class); +      Assert.fail("No KeyStore not detected"); + +    } catch (final BeansException e) { +      org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, +          e.getCause(), "Wrong exception"); +    } + +  } + +  @Test +  @DirtiesContext +  public void noKeyStore() { +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_KEYSTORE_PATH, +        "src/test/resources/config/notExist.p12"); +    try { +      context.getBean(IdAustriaClientAuthCredentialProvider.class); +      Assert.fail("No KeyStore not detected"); + +    } catch (final BeansException e) { +      final Optional<Throwable> eaafException = FluentIterable.from( +          Throwables.getCausalChain(e)).filter( +              Predicates.instanceOf(EaafConfigurationException.class)).first(); +      Assert.assertTrue("Wrong exception", eaafException.isPresent()); +      Assert.assertEquals("Wrong errorId", "internal.keystore.06", +          ((EaafException) eaafException.get()).getErrorId()); + +    } + +  } + +  @Test +  @DirtiesContext +  public void noWrongKeyStorePassword() { +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_KEYSTORE_PASSWORD, "test"); +    try { +      context.getBean(IdAustriaClientAuthCredentialProvider.class); +      Assert.fail("No KeyStore not detected"); + +    } catch (final BeansException e) { +      final Optional<Throwable> eaafException = FluentIterable.from( +          Throwables.getCausalChain(e)).filter( +              Predicates.instanceOf(EaafFactoryException.class)).first(); +      Assert.assertTrue("Wrong exception", eaafException.isPresent()); +      Assert.assertEquals("Wrong errorId", "internal.keystore.06", +          ((EaafException) eaafException.get()).getErrorId()); + +    } + +  } + +  @Test +  @DirtiesContext +  public void notKeyConfigurationWrongAlias() { +    final IdAustriaClientAuthCredentialProvider credential = context.getBean( +        IdAustriaClientAuthCredentialProvider.class); + +    Assert.assertNotNull("Credetialprovider", credential); +    Assert.assertNotNull("Friendlyname", credential.getFriendlyName()); + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_ALIAS, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMetaDataSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMessageSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_ALIAS, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMessageEncryptionCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +  } + +  @Test +  @DirtiesContext +  public void notKeyConfigurationWrongPassword() { +    final IdAustriaClientAuthCredentialProvider credential = context.getBean( +        IdAustriaClientAuthCredentialProvider.class); + +    Assert.assertNotNull("Credetialprovider", credential); +    Assert.assertNotNull("Friendlyname", credential.getFriendlyName()); + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_KEY_PASSWORD, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMetaDataSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_KEY_PASSWORD, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMessageSigningCredential(); +      Assert.fail("No message signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_KEY_PASSWORD, +          RandomStringUtils.randomAlphabetic(5)); +      final EaafX509Credential encCred = credential.getMessageEncryptionCredential(); +      Assert.assertNull("No encryption signing credentials not detected", encCred); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +  } + +  @Test +  @DirtiesContext +  public void notKeyConfigurationValidAliasWrongPassword() { +    final IdAustriaClientAuthCredentialProvider credential = context.getBean( +        IdAustriaClientAuthCredentialProvider.class); + +    Assert.assertNotNull("Credetialprovider", credential); +    Assert.assertNotNull("Friendlyname", credential.getFriendlyName()); + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_ALIAS, +          ALIAS_METADATA); +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_KEY_PASSWORD, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMetaDataSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS, +          ALIAS_SIGN); +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_KEY_PASSWORD, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMessageSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_ALIAS, +          ALIAS_ENC); +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_KEY_PASSWORD, +          RandomStringUtils.randomAlphabetic(5)); +      credential.getMessageEncryptionCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } +  } + +  @Test +  @DirtiesContext +  public void notKeyConfigurationWrongAliasValidPassword() { +    final IdAustriaClientAuthCredentialProvider credential = context.getBean( +        IdAustriaClientAuthCredentialProvider.class); + +    Assert.assertNotNull("Credetialprovider", credential); +    Assert.assertNotNull("Friendlyname", credential.getFriendlyName()); + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_ALIAS, +          RandomStringUtils.randomAlphabetic(5)); +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_KEY_PASSWORD, +          PASSWORD); +      credential.getMetaDataSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS, +          RandomStringUtils.randomAlphabetic(5)); +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_KEY_PASSWORD, +          PASSWORD); +      credential.getMessageSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_ALIAS, +          RandomStringUtils.randomAlphabetic(5)); +      config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_KEY_PASSWORD, +          PASSWORD); +      credential.getMessageEncryptionCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } +  } + +  @Test +  @DirtiesContext +  public void validonfiguration() throws CredentialsNotAvailableException { +    final IdAustriaClientAuthCredentialProvider credential = context.getBean( +        IdAustriaClientAuthCredentialProvider.class); + +    Assert.assertNotNull("Credetialprovider", credential); +    Assert.assertNotNull("Friendlyname", credential.getFriendlyName()); + +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_ALIAS, +        ALIAS_METADATA); +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_METADATA_KEY_PASSWORD, +        PASSWORD); +    credential.getMetaDataSigningCredential(); + +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS, +        ALIAS_SIGN); +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_KEY_PASSWORD, +        PASSWORD); +    credential.getMessageSigningCredential(); + +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_ALIAS, +        ALIAS_ENC); +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ENCRYPTION_KEY_PASSWORD, +        PASSWORD); +    credential.getMessageEncryptionCredential(); + +  } + +  @Test +  @DirtiesContext +  public void notKeyConfiguration() { +    final IdAustriaClientAuthCredentialProvider credential = context.getBean( +        IdAustriaClientAuthCredentialProvider.class); + +    Assert.assertNotNull("Credetialprovider", credential); +    Assert.assertNotNull("Friendlyname", credential.getFriendlyName()); + +    try { +      credential.getMetaDataSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      credential.getMessageSigningCredential(); +      Assert.fail("No message signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      final EaafX509Credential encCred = credential.getMessageEncryptionCredential(); +      Assert.assertNull("No encryption signing credentials not detected", encCred); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +  } + +  @Test +  @DirtiesContext +  public void notKeyConfigurationPkcs12() { +    config.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_KEYSTORE_PATH, +        "../keystore/pvp.p12"); +    final IdAustriaClientAuthCredentialProvider credential = context.getBean( +        IdAustriaClientAuthCredentialProvider.class); + +    Assert.assertNotNull("Credetialprovider", credential); +    Assert.assertNotNull("Friendlyname", credential.getFriendlyName()); + +    try { +      credential.getMetaDataSigningCredential(); +      Assert.fail("No Metadata signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      credential.getMessageSigningCredential(); +      Assert.fail("No message signing credentials not detected"); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } + +    try { +      final EaafX509Credential encCred = credential.getMessageEncryptionCredential(); +      Assert.assertNull("No encryption signing credentials not detected", encCred); + +    } catch (final CredentialsNotAvailableException e) { +      Assert.assertTrue("Wrong errorCode", e.getMessage().contains("internal.pvp.01")); + +    } +  } +} 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 175f95e6..e3757c0d 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 @@ -4,7 +4,7 @@ import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CON  import static org.mockito.ArgumentMatchers.any;  import static org.mockito.Mockito.times;  import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.when;  import java.net.URISyntaxException;  import java.security.KeyStore; @@ -18,7 +18,9 @@ import java.util.List;  import java.util.Map;  import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils;  import org.jetbrains.annotations.NotNull; +import org.joda.time.DateTime;  import org.jose4j.jwa.AlgorithmConstraints;  import org.jose4j.jwa.AlgorithmConstraints.ConstraintType;  import org.jose4j.jws.AlgorithmIdentifiers; @@ -28,7 +30,6 @@ import org.junit.Rule;  import org.junit.Test;  import org.junit.runner.RunWith;  import org.mockito.ArgumentCaptor; -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; @@ -41,15 +42,24 @@ import org.springframework.web.context.request.ServletRequestAttributes;  import com.fasterxml.jackson.databind.JsonNode;  import com.fasterxml.jackson.databind.ObjectMapper;  import com.github.skjolber.mockito.soap.SoapServiceRule; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet;  import at.asitplus.eidas.specific.connector.MsEidasNodeConstants;  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.MatchedPersonResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidPostProcessingException; +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.EidasAttributeRegistry; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.ICcSpecificEidProcessingService;  import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.EidasResponseUtils;  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.asitplus.eidas.specific.modules.auth.eidas.v2.utils.MatchingTaskUtils;  import at.gv.egiz.eaaf.core.api.IRequest;  import at.gv.egiz.eaaf.core.api.IRequestStorage;  import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; @@ -69,8 +79,10 @@ import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl;  import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl;  import at.gv.egiz.eaaf.core.impl.utils.Random;  import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.AttributeValue;  import eu.eidas.auth.commons.attribute.ImmutableAttributeMap;  import eu.eidas.auth.commons.attribute.ImmutableAttributeMap.Builder; +import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress;  import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse;  import lombok.val;  import szrservices.JwsHeaderParam; @@ -80,7 +92,6 @@ import szrservices.SignContentEntry;  import szrservices.SignContentResponseType;  @RunWith(SpringJUnit4ClassRunner.class) -@PrepareForTest(CreateIdentityLinkTask.class)  @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml", @@ -99,6 +110,9 @@ public class CreateIdentityLinkTaskEidNewTest {    EaafKeyStoreFactory keyStoreFactory;    @Autowired +  ICcSpecificEidProcessingService eidPostProcessor; +   +  @Autowired    private IRequestStorage requestStorage;    final ExecutionContext executionContext = new ExecutionContextImpl(); @@ -117,25 +131,27 @@ public class CreateIdentityLinkTaskEidNewTest {            AlgorithmIdentifiers.RSA_PSS_USING_SHA512));    private static ObjectMapper mapper = new ObjectMapper(); -   +    private AuthenticationResponse response; -   +    @Rule    public final SoapServiceRule soap = SoapServiceRule.newInstance();    /**     * jUnit test set-up. +   * @throws EidasAttributeException  +   * @throws EidPostProcessingException      */    @Before -  public void setUp() throws EaafStorageException, URISyntaxException { +  public void setUp() throws EaafStorageException, URISyntaxException, EidPostProcessingException, EidasAttributeException {      httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler");      httpResp = new MockHttpServletResponse();      RequestContextHolder.resetRequestAttributes();      RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false"); -     +      final Map<String, String> spConfig = new HashMap<>();      spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp");      spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); @@ -146,14 +162,20 @@ public class CreateIdentityLinkTaskEidNewTest {      response = buildDummyAuthResponse(false);      pendingReq.getSessionData(AuthProcessDataWrapper.class)          .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - +     +    final Map<String, Object> eidasAttributes = convertEidasAttrToSimpleMap( +        response.getAttributes().getAttributeMap());                   +    final SimpleEidasData eidData = eidPostProcessor.postProcess(eidasAttributes);     +    MatchingTaskUtils.storeInitialEidasData(pendingReq, eidData); +     +    MatchingTaskUtils.storeFinalMatchingResult(pendingReq, null);      pendingReq.setSpConfig(oaParam);      pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue());      pendingReq.setAuthUrl("http://test.com/");      pendingReq.setTransactionId("avaasbav");      pendingReq.setPiiTransactionId(RandomStringUtils.randomAlphanumeric(10)); -         +      executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "XX");      executionContext.put(EaafConstants.PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT, true); @@ -165,27 +187,29 @@ public class CreateIdentityLinkTaskEidNewTest {      //initialize test      response = buildDummyAuthResponse(true);      pendingReq.getSessionData(AuthProcessDataWrapper.class) -        .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); +        .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response);     +    MatchingTaskUtils.storeInitialEidasData(pendingReq, eidPostProcessor.postProcess( +        convertEidasAttrToSimpleMap(response.getAttributes().getAttributeMap())));      String vsz = RandomStringUtils.randomNumeric(10); -    when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(vsz); +    when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(vsz);      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); +    when(szrMock.signContent(any(), any(), any())).thenReturn(signContentResp);      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -     +      //perform test      task.execute(pendingReq, executionContext); -    //validate state     +    //validate state      // check if pendingRequest was stored      IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId());      Assert.assertNotNull("pendingReq not stored", storedPendingReq); -     +      //check data in session      final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class);      Assert.assertNotNull("AuthProcessData", authProcessData); @@ -193,16 +217,12 @@ public class CreateIdentityLinkTaskEidNewTest {      String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class);      Assert.assertNotNull("AuthBlock", authBlock); -     +      Assert.assertTrue("EID process", authProcessData.isEidProcess());      Assert.assertTrue("foreigner process", authProcessData.isForeigner()); -    Assert.assertEquals("EID-ISSUING_NATION", "LU",  +    Assert.assertEquals("EID-ISSUING_NATION", "LU",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); -    Assert.assertNotNull("LoA is null", authProcessData.getQaaLevel()); -    Assert.assertEquals("LoA", response.getLevelOfAssurance(),  -        authProcessData.getQaaLevel()); -         -     +      // check authblock signature      final AlgorithmConstraints constraints = new AlgorithmConstraints(ConstraintType.PERMIT,          BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.toArray(new String[BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.size()])); @@ -210,60 +230,61 @@ public class CreateIdentityLinkTaskEidNewTest {      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());         -    JsonNode authBlockJson = mapper.readTree(result.getPayLoad());     +    Assert.assertTrue("AuthBlock not valid", result.isValid()); +    JsonNode authBlockJson = mapper.readTree(result.getPayLoad());      Assert.assertNotNull("deserialized AuthBlock", authBlockJson); -     -    Assert.assertNotNull("no piiTransactionId in pendingRequesdt",  + +    Assert.assertNotNull("no piiTransactionId in pendingRequesdt",          storedPendingReq.getUniquePiiTransactionIdentifier()); -    Assert.assertEquals("piiTransactionId", storedPendingReq.getUniquePiiTransactionIdentifier(),  +    Assert.assertEquals("piiTransactionId", storedPendingReq.getUniquePiiTransactionIdentifier(),          authBlockJson.get("piiTransactionId").asText()); -    Assert.assertEquals("appId", randomTestSp, authBlockJson.get("appId").asText());     +    Assert.assertEquals("appId", randomTestSp, authBlockJson.get("appId").asText());      Assert.assertFalse("'challenge' is null", authBlockJson.get("challenge").asText().isEmpty());      Assert.assertFalse("'timestamp' is null", authBlockJson.get("timestamp").asText().isEmpty());      Assert.assertFalse("binding pubKey", authBlockJson.has("bindingPublicKey")); +      // check vsz request      ArgumentCaptor<PersonInfoType> argument4 = ArgumentCaptor.forClass(PersonInfoType.class); -    ArgumentCaptor<Boolean> argument5 = ArgumentCaptor.forClass(Boolean.class);         +    ArgumentCaptor<Boolean> argument5 = ArgumentCaptor.forClass(Boolean.class);      verify(szrMock, times(1)).getStammzahlEncrypted(argument4.capture(), argument5.capture()); -     +      Boolean param5 = argument5.getValue(); -    Assert.assertTrue("insertERnP flag", param5);     +    Assert.assertTrue("insertERnP flag", param5);      PersonInfoType person = argument4.getValue(); -    Assert.assertEquals("FamilyName",  +    Assert.assertEquals("FamilyName",          response.getAttributes().getAttributeValuesByFriendlyName("FamilyName").getFirstValue( -            response.getAttributes().getDefinitionsByFriendlyName("FamilyName").iterator().next()),  +            response.getAttributes().getDefinitionsByFriendlyName("FamilyName").iterator().next()),          person.getPerson().getName().getFamilyName()); -    Assert.assertEquals("GivenName",  +    Assert.assertEquals("GivenName",          response.getAttributes().getAttributeValuesByFriendlyName("FirstName").getFirstValue( -            response.getAttributes().getDefinitionsByFriendlyName("FirstName").iterator().next()),  +            response.getAttributes().getDefinitionsByFriendlyName("FirstName").iterator().next()),          person.getPerson().getName().getGivenName()); -    Assert.assertEquals("DateOfBirth",  +    Assert.assertEquals("DateOfBirth",          response.getAttributes().getAttributeValuesByFriendlyName("DateOfBirth").getFirstValue(              response.getAttributes().getDefinitionsByFriendlyName("DateOfBirth").iterator().next()) -            .toString().split("T")[0],  +            .toString().split("T")[0],          person.getPerson().getDateOfBirth()); -     -    Assert.assertEquals("PlaceOfBirth",  + +    Assert.assertEquals("PlaceOfBirth",          response.getAttributes().getAttributeValuesByFriendlyName("PlaceOfBirth").getFirstValue( -            response.getAttributes().getDefinitionsByFriendlyName("PlaceOfBirth").iterator().next()),  -        person.getPerson().getPlaceOfBirth());     -    Assert.assertEquals("BirthName",  +            response.getAttributes().getDefinitionsByFriendlyName("PlaceOfBirth").iterator().next()), +        person.getPerson().getPlaceOfBirth()); +    Assert.assertEquals("BirthName",          response.getAttributes().getAttributeValuesByFriendlyName("BirthName").getFirstValue( -            response.getAttributes().getDefinitionsByFriendlyName("BirthName").iterator().next()),  +            response.getAttributes().getDefinitionsByFriendlyName("BirthName").iterator().next()),          person.getPerson().getAlternativeName().getFamilyName()); -     +      Assert.assertEquals("CitizenCountry", "LU", person.getTravelDocument().getIssuingCountry());      Assert.assertEquals("DocumentType", "ELEKTR_DOKUMENT", person.getTravelDocument().getDocumentType()); -     -    Assert.assertEquals("Identifier",  + +    Assert.assertEquals("Identifier",          response.getAttributes().getAttributeValuesByFriendlyName("PersonIdentifier").getFirstValue(              response.getAttributes().getDefinitionsByFriendlyName("PersonIdentifier").iterator().next()) -            .toString().split("/")[2],  +            .toString().split("/")[2],          person.getTravelDocument().getDocumentNumber()); -            +      // check bcBind singing request      ArgumentCaptor<Boolean> argument1 = ArgumentCaptor.forClass(Boolean.class);      ArgumentCaptor<List<JwsHeaderParam>> argument2 = ArgumentCaptor.forClass(List.class); @@ -271,62 +292,76 @@ public class CreateIdentityLinkTaskEidNewTest {      verify(szrMock, times(1)).signContent(argument1.capture(), argument2.capture(), argument3.capture());      Boolean param1 = argument1.getValue();      Assert.assertFalse("addCert flag", param1); -     +      List<JwsHeaderParam> param2 = argument2.getValue(); -    Assert.assertNotNull("JWS Headers", param2);  +    Assert.assertNotNull("JWS Headers", param2);      Assert.assertFalse("JWS Headers empty", param2.isEmpty());      Assert.assertEquals("Wrong JWS header size", 1, param2.size());      Assert.assertEquals("Missing JWS header key", "urn:at.gv.eid:bindtype", param2.get(0).getKey());      Assert.assertEquals("Missing JWS header value", "urn:at.gv.eid:eidasBind", param2.get(0).getValue()); -     +      List<SignContentEntry> param3 = argument3.getValue();      Assert.assertNotNull("sign Payload", param3); -    Assert.assertEquals("wrong sign-payload size", 1, param3.size());     -    Assert.assertNotNull("payload", param3.get(0).getValue().getBytes());     +    Assert.assertEquals("wrong sign-payload size", 1, param3.size()); +    Assert.assertNotNull("payload", param3.get(0).getValue().getBytes());      JsonNode bcBind = mapper.readTree(param3.get(0).getValue().getBytes());      Assert.assertNotNull("bcbind req", bcBind); -     +      Assert.assertEquals("vsz", vsz, bcBind.get("urn:eidgvat:attributes.vsz.value").asText()); -    Assert.assertEquals("eid status", "urn:eidgvat:eid.status.eidas",  +    Assert.assertEquals("eid status", "urn:eidgvat:eid.status.eidas",          bcBind.get("urn:eidgvat:attributes.eid.status").asText());      Assert.assertTrue("pubKeys", bcBind.has("urn:eidgvat:attributes.user.pubkeys")); -    Assert.assertTrue("pubKeys", bcBind.get("urn:eidgvat:attributes.user.pubkeys").isArray());     +    Assert.assertTrue("pubKeys", bcBind.get("urn:eidgvat:attributes.user.pubkeys").isArray());      Iterator<JsonNode> pubKeys = bcBind.get("urn:eidgvat:attributes.user.pubkeys").elements();      Assert.assertTrue("No PubKey", pubKeys.hasNext()); -    Assert.assertEquals("Wrong pubKey",  +    Assert.assertEquals("Wrong pubKey",          "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmxcB5jnrAwGn7xjgVFv1UBUv1pluwDRFQx7x5O6rSn7pblYfwaWeKa8y"          + "jS5BDDaZ00mhhnSlm2XByNrkg5yBGetTgBGtQVAxV5apfuAWN8TS3uSXgdZol7Khd6kraUITtnulvLe8tNaboom5P0zN6UxbJN"          + "NVLishVp80HiRXiDbplCTUk8b5cYtmivdb0+5JBTa7L5N/anRVnHHoJCXgNPTouO8daUHZbG1mPk0HgqD8rhZ+OBzE+APKH9No" -        + "agedSrGRDLdIgZxkrg0mxmfsZQIi2wdJSi3y0PAjEps/s4j0nmw9bPRgCMNLBqqjxtN5JKC8E1yyLm7YefXv/nPaMwIDAQAB",  +        + "agedSrGRDLdIgZxkrg0mxmfsZQIi2wdJSi3y0PAjEps/s4j0nmw9bPRgCMNLBqqjxtN5JKC8E1yyLm7YefXv/nPaMwIDAQAB",          pubKeys.next().asText());      Assert.assertFalse("More than one PubKey", pubKeys.hasNext()); -     +    }    @Test -  public void successfulProcessWithStandardInfos() throws Exception { -    //initialize test     +  public void successfulProcessWithDataFromMatching() throws Exception { +    //initialize test      String vsz = RandomStringUtils.randomNumeric(10); -    when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(vsz); +    when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(vsz);      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); -     + +    when(szrMock.signContent(any(), any(), any())).thenReturn(signContentResp); + +      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      String bindingPubKey = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); + +    MatchedPersonResult matchingInfos = MatchedPersonResult.builder() +        .bpk(RandomStringUtils.randomAlphabetic(5)) +        .givenName(RandomStringUtils.randomAlphabetic(5)) +        .familyName(RandomStringUtils.randomAlphabetic(5)) +        .dateOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .countryCode(RandomStringUtils.randomAlphabetic(2).toUpperCase()) +        .build();         +    MatchingTaskUtils.storeFinalMatchingResult(pendingReq, matchingInfos); +      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.EID_BINDING_PUBLIC_KEY_NAME, bindingPubKey); +      //perform test      task.execute(pendingReq, executionContext); - -    //validate state     +     +     +    //validate state      // check if pendingRequest was stored      IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId());      Assert.assertNotNull("pendingReq not stored", storedPendingReq); -     +      //check data in session      final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class);      Assert.assertNotNull("AuthProcessData", authProcessData); @@ -335,6 +370,7 @@ public class CreateIdentityLinkTaskEidNewTest {      // check authblock signature      String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class);      Assert.assertNotNull("AuthBlock", authBlock); +      final AlgorithmConstraints constraints = new AlgorithmConstraints(ConstraintType.PERMIT,          BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.toArray(new String[BINDING_AUTH_ALGORITHM_WHITELIST_SIGNING.size()]));      Pair<KeyStore, Provider> keyStore = getKeyStore(); @@ -357,53 +393,115 @@ public class CreateIdentityLinkTaskEidNewTest {      Assert.assertTrue("EID process", authProcessData.isEidProcess());      Assert.assertTrue("foreigner process", authProcessData.isForeigner()); -    Assert.assertEquals("EID-ISSUING_NATION", "LU",  +    Assert.assertEquals("EID-ISSUING_NATION", "LU",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); -    Assert.assertNotNull("LoA is null", authProcessData.getQaaLevel()); -    Assert.assertEquals("LoA", response.getLevelOfAssurance(),  -        authProcessData.getQaaLevel()); -       +      // check vsz request      ArgumentCaptor<PersonInfoType> argument4 = ArgumentCaptor.forClass(PersonInfoType.class); -    ArgumentCaptor<Boolean> argument5 = ArgumentCaptor.forClass(Boolean.class);         +    ArgumentCaptor<Boolean> argument5 = ArgumentCaptor.forClass(Boolean.class);      verify(szrMock, times(1)).getStammzahlEncrypted(argument4.capture(), argument5.capture()); + +    Boolean param5 = argument5.getValue(); +    Assert.assertFalse("insertERnP flag", param5); +    PersonInfoType person = argument4.getValue(); +    Assert.assertEquals("FamilyName", +        matchingInfos.getFamilyName(), +        person.getPerson().getName().getFamilyName()); +    Assert.assertEquals("GivenName", +        matchingInfos.getGivenName(), +        person.getPerson().getName().getGivenName()); +    Assert.assertEquals("DateOfBirth", +        matchingInfos.getDateOfBirth(), +        person.getPerson().getDateOfBirth()); +    Assert.assertEquals("bPK", +        matchingInfos.getBpk(), +        person.getPerson().getIdentification().getValue()); +    Assert.assertEquals("bPKType", +        EaafConstants.URN_PREFIX_CDID + "ZP", +        person.getPerson().getIdentification().getType()); +     +    Assert.assertNull("PlaceOfBirth", person.getPerson().getPlaceOfBirth()); +    Assert.assertNull("BirthName", person.getPerson().getAlternativeName()); +             +  } +   +  @Test +  public void successfulProcessWithStandardInfos() throws Exception { +    //initialize test +    String vsz = RandomStringUtils.randomNumeric(10); +    when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(vsz); +    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); + +    String randomTestSp = RandomStringUtils.randomAlphabetic(10); +    pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); + +    //perform test +    task.execute(pendingReq, executionContext); + +    //validate state +    // check if pendingRequest was stored +    IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId()); +    Assert.assertNotNull("pendingReq not stored", storedPendingReq); + +    //check data in session +    final AuthProcessDataWrapper authProcessData = storedPendingReq.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); + +    Assert.assertTrue("EID process", authProcessData.isEidProcess()); +    Assert.assertTrue("foreigner process", authProcessData.isForeigner()); +    Assert.assertEquals("EID-ISSUING_NATION", "LU", +        authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); + +    // check vsz request +    ArgumentCaptor<PersonInfoType> argument4 = ArgumentCaptor.forClass(PersonInfoType.class); +    ArgumentCaptor<Boolean> argument5 = ArgumentCaptor.forClass(Boolean.class); +    verify(szrMock, times(1)).getStammzahlEncrypted(argument4.capture(), argument5.capture()); +      Boolean param5 = argument5.getValue(); -    Assert.assertTrue("insertERnP flag", param5);     +    Assert.assertTrue("insertERnP flag", param5);      PersonInfoType person = argument4.getValue(); -    Assert.assertEquals("FamilyName",  +    Assert.assertEquals("FamilyName",          response.getAttributes().getAttributeValuesByFriendlyName("FamilyName").getFirstValue( -            response.getAttributes().getDefinitionsByFriendlyName("FamilyName").iterator().next()),  +            response.getAttributes().getDefinitionsByFriendlyName("FamilyName").iterator().next()),          person.getPerson().getName().getFamilyName()); -    Assert.assertEquals("GivenName",  +    Assert.assertEquals("GivenName",          response.getAttributes().getAttributeValuesByFriendlyName("FirstName").getFirstValue( -            response.getAttributes().getDefinitionsByFriendlyName("FirstName").iterator().next()),  +            response.getAttributes().getDefinitionsByFriendlyName("FirstName").iterator().next()),          person.getPerson().getName().getGivenName()); -    Assert.assertEquals("DateOfBirth",  +    Assert.assertEquals("DateOfBirth",          response.getAttributes().getAttributeValuesByFriendlyName("DateOfBirth").getFirstValue(              response.getAttributes().getDefinitionsByFriendlyName("DateOfBirth").iterator().next()) -            .toString().split("T")[0],  +            .toString().split("T")[0],          person.getPerson().getDateOfBirth()); -     -    Assert.assertNull("PlaceOfBirth", person.getPerson().getPlaceOfBirth());      + +    Assert.assertNull("PlaceOfBirth", person.getPerson().getPlaceOfBirth());      Assert.assertNull("BirthName", person.getPerson().getAlternativeName()); -     +      Assert.assertEquals("CitizenCountry", "LU", person.getTravelDocument().getIssuingCountry());      Assert.assertEquals("DocumentType", "ELEKTR_DOKUMENT", person.getTravelDocument().getDocumentType()); -     -    Assert.assertEquals("Identifier",  + +    Assert.assertEquals("Identifier",          response.getAttributes().getAttributeValuesByFriendlyName("PersonIdentifier").getFirstValue(              response.getAttributes().getDefinitionsByFriendlyName("PersonIdentifier").iterator().next()) -            .toString().split("/")[2],  +            .toString().split("/")[2],          person.getTravelDocument().getDocumentNumber()); -            -    + +    } -   +    @Test    public void getStammzahlEncryptedExceptionTest() throws Exception {      try { -      when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(null); +      when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(null);        task.execute(pendingReq, executionContext);      } catch (TaskExecutionException e) {        Assert.assertEquals("Incorrect exception thrown", e.getMessage(), @@ -417,8 +515,8 @@ public class CreateIdentityLinkTaskEidNewTest {    @Test    public void signContentExceptionTest() throws Exception {      try { -      when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(RandomStringUtils.randomNumeric(10)); -      when(szrMock, "signContent", any(), any(), any()).thenReturn(null); +      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(), @@ -465,7 +563,7 @@ public class CreateIdentityLinkTaskEidNewTest {          Constants.eIDAS_ATTR_PLACEOFBIRTH).first();      final AttributeDefinition attributeDef6 = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(          Constants.eIDAS_ATTR_BIRTHNAME).first(); -    +      final Builder attributeMap = ImmutableAttributeMap.builder();      attributeMap.put(attributeDef, "LU/AT/" + RandomStringUtils.randomNumeric(64));      attributeMap.put(attributeDef2, RandomStringUtils.randomAlphabetic(10)); @@ -474,7 +572,7 @@ public class CreateIdentityLinkTaskEidNewTest {      if (withAll) {        attributeMap.put(attributeDef5, RandomStringUtils.randomAlphabetic(10));        attributeMap.put(attributeDef6, RandomStringUtils.randomAlphabetic(10)); -       +      }      val b = new AuthenticationResponse.Builder(); @@ -488,4 +586,53 @@ public class CreateIdentityLinkTaskEidNewTest {          .attributes(attributeMap.build())          .build();    } +   +  private Map<String, Object> convertEidasAttrToSimpleMap( +      ImmutableMap<AttributeDefinition<?>, ImmutableSet<? extends AttributeValue<?>>> attributeMap) { +    final Map<String, Object> result = new HashMap<>(); +    for (final AttributeDefinition<?> el : attributeMap.keySet()) { +      final Class<?> parameterizedType = el.getParameterizedType(); +      if (DateTime.class.equals(parameterizedType)) { +        convertDateTime(attributeMap, result, el); +      } else if (PostalAddress.class.equals(parameterizedType)) { +        convertPostalAddress(attributeMap, result, el); +      } else { +        convertString(attributeMap, result, el); +      } +    } +    return result; +  } + +  private void convertString(ImmutableMap<AttributeDefinition<?>, +                             ImmutableSet<? extends AttributeValue<?>>> attributeMap, +                             Map<String, Object> result, AttributeDefinition<?> el) { +    final List<String> natPersonIdObj = EidasResponseUtils +        .translateStringListAttribute(el, attributeMap.get(el)); +    final String stringAttr = natPersonIdObj.get(0); +    if (StringUtils.isNotEmpty(stringAttr)) { +      result.put(el.getFriendlyName(), stringAttr); + +    } +  } + +  private void convertPostalAddress(ImmutableMap<AttributeDefinition<?>, +                                    ImmutableSet<? extends AttributeValue<?>>> attributeMap, +                                    Map<String, Object> result, AttributeDefinition<?> el) { +    final PostalAddress addressAttribute = EidasResponseUtils +        .translateAddressAttribute(el, attributeMap.get(el).asList()); +    if (addressAttribute != null) { +      result.put(el.getFriendlyName(), addressAttribute); + +    } +  } + +  private void convertDateTime(ImmutableMap<AttributeDefinition<?>, +                               ImmutableSet<? extends AttributeValue<?>>> attributeMap, +                               Map<String, Object> result, AttributeDefinition<?> el) { +    final DateTime attribute = EidasResponseUtils.translateDateAttribute(el, attributeMap.get(el).asList()); +    if (attribute != null) { +      result.put(el.getFriendlyName(), attribute); + +    } +  }  } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskTest.java index e880178f..7513501e 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/CreateIdentityLinkTaskTest.java @@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.any;  import java.net.URISyntaxException;  import java.util.HashMap; +import java.util.List;  import java.util.Map;  import javax.xml.bind.JAXBContext; @@ -12,13 +13,14 @@ import javax.xml.bind.JAXBException;  import javax.xml.bind.Unmarshaller;  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.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; @@ -29,12 +31,21 @@ import org.springframework.web.context.request.RequestContextHolder;  import org.springframework.web.context.request.ServletRequestAttributes;  import com.github.skjolber.mockito.soap.SoapServiceRule; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet;  import at.asitplus.eidas.specific.connector.MsEidasNodeConstants;  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.MatchedPersonResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidPostProcessingException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasAttributeException;  import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.ICcSpecificEidProcessingService;  import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.EidasResponseUtils; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.MatchingTaskUtils;  import at.gv.egiz.eaaf.core.api.IRequest;  import at.gv.egiz.eaaf.core.api.IRequestStorage;  import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; @@ -51,7 +62,9 @@ import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl;  import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl;  import at.gv.egiz.eaaf.core.impl.utils.Random;  import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.AttributeValue;  import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; +import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress;  import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse;  import lombok.val;  import szrservices.GetBPK; @@ -62,7 +75,6 @@ import szrservices.SZR;  import szrservices.SZRException_Exception;  @RunWith(SpringJUnit4ClassRunner.class) -@PrepareForTest(CreateIdentityLinkTask.class)  @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml", @@ -81,7 +93,10 @@ public class CreateIdentityLinkTaskTest {    EaafKeyStoreFactory keyStoreFactory;    @Autowired -  private IRequestStorage requestStorage; +  ICcSpecificEidProcessingService eidPostProcessor; +   +  @Autowired +  IRequestStorage requestStorage;    final ExecutionContext executionContext = new ExecutionContextImpl();    private MockHttpServletRequest httpReq; @@ -89,18 +104,20 @@ public class CreateIdentityLinkTaskTest {    private TestRequestImpl pendingReq;    private DummySpConfiguration oaParam;    private SZR szrMock; -   +    private AuthenticationResponse response;    private Map<String, String> spConfig; -   +    @Rule    public final SoapServiceRule soap = SoapServiceRule.newInstance();    /**     * jUnit test set-up. +   * @throws EidasAttributeException  +   * @throws EidPostProcessingException      */    @Before -  public void setUp() throws EaafStorageException, URISyntaxException { +  public void setUp() throws EaafStorageException, URISyntaxException, EidPostProcessingException, EidasAttributeException {      httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler");      httpResp = new MockHttpServletResponse(); @@ -110,7 +127,7 @@ public class CreateIdentityLinkTaskTest {      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.revisionlog.eidmapping.active", "false");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.params.useSZRForbPKCalculation", "false"); -     +      spConfig = new HashMap<>();      spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp");      spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); @@ -119,42 +136,48 @@ public class CreateIdentityLinkTaskTest {      pendingReq = new TestRequestImpl();      response = buildDummyAuthResponse(); - +    final Map<String, Object> eidasAttributes = convertEidasAttrToSimpleMap( +        response.getAttributes().getAttributeMap());                   +    final SimpleEidasData eidData = eidPostProcessor.postProcess(eidasAttributes);     +    MatchingTaskUtils.storeInitialEidasData(pendingReq, eidData);      pendingReq.getSessionData(AuthProcessDataWrapper.class)          .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); +     +    MatchingTaskUtils.storeFinalMatchingResult(pendingReq, null); +          pendingReq.setSpConfig(oaParam);      pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue());      pendingReq.setAuthUrl("http://test.com/");      pendingReq.setTransactionId("avaasbav");      pendingReq.setPiiTransactionId(RandomStringUtils.randomAlphanumeric(10)); -         +      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");    } -     +    @Test    public void buildIdentityLink() throws Exception { -    //initialize test    +    //initialize test      setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml"); -      +      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false"); -     -     + +      //perform test      task.execute(pendingReq, executionContext); -     -    //validate state     + +    //validate state      // check if pendingRequest was stored      IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId());      Assert.assertNotNull("pendingReq not stored", storedPendingReq); -     +      //check data in session      final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class);      Assert.assertNotNull("AuthProcessData", authProcessData); @@ -162,15 +185,12 @@ public class CreateIdentityLinkTaskTest {      String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class);      Assert.assertNull("AuthBlock", authBlock); -     +      Assert.assertFalse("EID process", authProcessData.isEidProcess());      Assert.assertTrue("foreigner process", authProcessData.isForeigner()); -    Assert.assertEquals("EID-ISSUING_NATION", "LU",  +    Assert.assertEquals("EID-ISSUING_NATION", "LU",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); -    Assert.assertNotNull("LoA is null", authProcessData.getQaaLevel()); -    Assert.assertEquals("LoA", response.getLevelOfAssurance(),  -        authProcessData.getQaaLevel()); -         +      Assert.assertNotNull("IDL", authProcessData.getIdentityLink());      checkElement("Mustermann", authProcessData.getIdentityLink().getFamilyName());      checkElement("Hans", authProcessData.getIdentityLink().getGivenName()); @@ -178,12 +198,69 @@ public class CreateIdentityLinkTaskTest {      checkElement("urn:publicid:gv.at:baseid", authProcessData.getIdentityLink().getIdentificationType());      checkElement("k+zDM1BVpN1WJO4x7ZQ3ng==", authProcessData.getIdentityLink().getIdentificationValue());      Assert.assertNotNull(authProcessData.getIdentityLink().getSerializedSamlAssertion()); -    Assert.assertNotNull(authProcessData.getIdentityLink().getSamlAssertion());     -    +    Assert.assertNotNull(authProcessData.getIdentityLink().getSamlAssertion()); +      Assert.assertNotNull("no bPK", authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); -    Assert.assertEquals("wrong bPK", "XX:FkXtOaSSeR3elyL9KLLvijIYDMU=",  +    Assert.assertEquals("wrong bPK", "XX:FkXtOaSSeR3elyL9KLLvijIYDMU=",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); + +  } + +  @Test +  public void successfulProcessWithDataFromMatching() throws Exception { +    //initialize test +    setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml"); + +    String randomTestSp = RandomStringUtils.randomAlphabetic(10); +    pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); + +    basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false"); + +    MatchedPersonResult matchingInfos = MatchedPersonResult.builder() +        .bpk(RandomStringUtils.randomAlphabetic(5)) +        .givenName(RandomStringUtils.randomAlphabetic(5)) +        .familyName(RandomStringUtils.randomAlphabetic(5)) +        .dateOfBirth(RandomStringUtils.randomAlphabetic(5)) +        .countryCode(RandomStringUtils.randomAlphabetic(2).toUpperCase()) +        .build(); +         +    MatchingTaskUtils.storeFinalMatchingResult(pendingReq, matchingInfos); +     +    //perform test +    task.execute(pendingReq, executionContext); +     +    //validate state +    // check if pendingRequest was stored +    IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId()); +    Assert.assertNotNull("pendingReq not stored", storedPendingReq); + +    //check data in session +    final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class); +    Assert.assertNotNull("AuthProcessData", authProcessData); +    Assert.assertNull("eidasBind", authProcessData.getGenericDataFromSession(Constants.EIDAS_BIND, String.class)); + +    String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class); +    Assert.assertNull("AuthBlock", authBlock); + +    Assert.assertFalse("EID process", authProcessData.isEidProcess()); +    Assert.assertTrue("foreigner process", authProcessData.isForeigner()); +    Assert.assertEquals("EID-ISSUING_NATION", "LU", +        authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); + +    Assert.assertNotNull("IDL", authProcessData.getIdentityLink()); +    checkElement("Mustermann", authProcessData.getIdentityLink().getFamilyName()); +    checkElement("Hans", authProcessData.getIdentityLink().getGivenName()); +    checkElement("1989-05-05", authProcessData.getIdentityLink().getDateOfBirth()); +    checkElement("urn:publicid:gv.at:baseid", authProcessData.getIdentityLink().getIdentificationType()); +    checkElement("k+zDM1BVpN1WJO4x7ZQ3ng==", authProcessData.getIdentityLink().getIdentificationValue()); +    Assert.assertNotNull(authProcessData.getIdentityLink().getSerializedSamlAssertion()); +    Assert.assertNotNull(authProcessData.getIdentityLink().getSamlAssertion()); + +    Assert.assertNotNull("no bPK", authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); +    Assert.assertEquals("wrong bPK", "XX:FkXtOaSSeR3elyL9KLLvijIYDMU=", +        authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); +                }    @Test @@ -191,22 +268,22 @@ public class CreateIdentityLinkTaskTest {      //initialize test      setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml");      spConfig.put("target", EaafConstants.URN_PREFIX_WBPK + "FN+123456i"); -     +      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.revisionlog.eidmapping.active", "true"); -     +      //perform test      task.execute(pendingReq, executionContext); -     -    //validate state     + +    //validate state      // check if pendingRequest was stored      IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId());      Assert.assertNotNull("pendingReq not stored", storedPendingReq); -     +      //check data in session      final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class);      Assert.assertNotNull("AuthProcessData", authProcessData); @@ -214,42 +291,39 @@ public class CreateIdentityLinkTaskTest {      String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class);      Assert.assertNull("AuthBlock", authBlock); -     +      Assert.assertFalse("EID process", authProcessData.isEidProcess());      Assert.assertTrue("foreigner process", authProcessData.isForeigner()); -    Assert.assertEquals("EID-ISSUING_NATION", "LU",  +    Assert.assertEquals("EID-ISSUING_NATION", "LU",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); -    Assert.assertNotNull("LoA is null", authProcessData.getQaaLevel()); -    Assert.assertEquals("LoA", response.getLevelOfAssurance(),  -        authProcessData.getQaaLevel()); -    +      Assert.assertNotNull("no bPK", authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); -    Assert.assertEquals("wrong bPK", "FN+123456i:D26vJncPS2W790RH/LP04V+vNOQ=",  +    Assert.assertEquals("wrong bPK", "FN+123456i:D26vJncPS2W790RH/LP04V+vNOQ=",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); -     +    } -   +    @Test    public void buildIdentityLinkWithEidasBpk() throws Exception {      //initialize test      setSzrResponseIdentityLink("/data/szr/szr_resp_valid_2.xml");      spConfig.put("target", EaafConstants.URN_PREFIX_EIDAS + "AT+EU"); -     +      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.revisionlog.eidmapping.active", "true"); -     +      //perform test      task.execute(pendingReq, executionContext); -     -    //validate state     + +    //validate state      // check if pendingRequest was stored      IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId());      Assert.assertNotNull("pendingReq not stored", storedPendingReq); -     +      //check data in session      final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class);      Assert.assertNotNull("AuthProcessData", authProcessData); @@ -257,80 +331,77 @@ public class CreateIdentityLinkTaskTest {      String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class);      Assert.assertNull("AuthBlock", authBlock); -     +      Assert.assertFalse("EID process", authProcessData.isEidProcess());      Assert.assertTrue("foreigner process", authProcessData.isForeigner()); -    Assert.assertEquals("EID-ISSUING_NATION", "LU",  +    Assert.assertEquals("EID-ISSUING_NATION", "LU",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); -    Assert.assertNotNull("LoA is null", authProcessData.getQaaLevel()); -    Assert.assertEquals("LoA", response.getLevelOfAssurance(),  -        authProcessData.getQaaLevel()); -    +      Assert.assertNotNull("IDL", authProcessData.getIdentityLink());      checkElement("Musterfrau", authProcessData.getIdentityLink().getFamilyName());      checkElement("Martina", authProcessData.getIdentityLink().getGivenName());      checkElement("1991-04-15", authProcessData.getIdentityLink().getDateOfBirth());      checkElement("urn:publicid:gv.at:baseid", authProcessData.getIdentityLink().getIdentificationType());      checkElement("k+zDM1BV1312312332x7ZQ3ng==", authProcessData.getIdentityLink().getIdentificationValue()); -     +      Assert.assertNotNull("no bPK", authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); -    Assert.assertEquals("wrong bPK", "AT+EU:AT/EU/1+wqDl059/02Ptny0g+LyuLDJV0=",  +    Assert.assertEquals("wrong bPK", "AT+EU:AT/EU/1+wqDl059/02Ptny0g+LyuLDJV0=",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); -     +    } -   +    @Test    public void buildIdentityLinkWithUnknownBpk() throws Exception {      //initialize test      setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml");      spConfig.put("target", "urn:notextis:1234"); -     +      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.revisionlog.eidmapping.active", "true"); -     +      try {        task.execute(pendingReq, executionContext);        Assert.fail("unknown bPKType not detected"); -       +      } catch (TaskExecutionException e) { -      Assert.assertEquals("ErrorId", "builder.33",  +      Assert.assertEquals("ErrorId", "builder.33",            ((EaafException) e.getOriginalException()).getErrorId());        Assert.assertEquals("wrong parameter size", 1, ((EaafException) e.getOriginalException())            .getParams().length); -    }       +    }    } -   +    @Test    public void noBpkResult() throws Exception {      //initialize test      setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml");      GetBPKResponse getBpkResp = new GetBPKResponse();      org.mockito.Mockito.when(szrMock.getBPK(any(GetBPK.class))).thenReturn(getBpkResp ); -     +      spConfig.put("target", "urn:notextis:1234"); -     +      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.revisionlog.eidmapping.active", "true");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.params.useSZRForbPKCalculation", "true"); -     +      try {        task.execute(pendingReq, executionContext);        Assert.fail("unknown bPKType not detected"); -       +      } catch (TaskExecutionException e) { -      Assert.assertEquals("ErrorId", "ernb.01",  +      Assert.assertEquals("ErrorId", "ernb.01",            ((EaafException) e.getOriginalException()).getErrorId()); -       -    }       + +    }    } -   +    @Test    public void bPKFromSzr() throws Exception {      //initialize test @@ -339,25 +410,25 @@ public class CreateIdentityLinkTaskTest {      GetBPKResponse getBpkResp = new GetBPKResponse();      getBpkResp.getGetBPKReturn().add(bpk);      org.mockito.Mockito.when(szrMock.getBPK(any(GetBPK.class))).thenReturn(getBpkResp ); -     +      spConfig.put("target", "urn:notextis:1234"); -     +      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.revisionlog.eidmapping.active", "true");      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.params.useSZRForbPKCalculation", "true"); -     +      //execute test        task.execute(pendingReq, executionContext); -      -       -      //validate state     + + +      //validate state        // check if pendingRequest was stored        IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId());        Assert.assertNotNull("pendingReq not stored", storedPendingReq); -       +        //check data in session        final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class);        Assert.assertNotNull("AuthProcessData", authProcessData); @@ -365,38 +436,35 @@ public class CreateIdentityLinkTaskTest {        String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class);        Assert.assertNull("AuthBlock", authBlock); -       +        Assert.assertFalse("EID process", authProcessData.isEidProcess());        Assert.assertTrue("foreigner process", authProcessData.isForeigner()); -      Assert.assertEquals("EID-ISSUING_NATION", "LU",  +      Assert.assertEquals("EID-ISSUING_NATION", "LU",            authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); -      Assert.assertNotNull("LoA is null", authProcessData.getQaaLevel()); -      Assert.assertEquals("LoA", response.getLevelOfAssurance(),  -          authProcessData.getQaaLevel()); -       +        Assert.assertNotNull("no bPK", authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME)); -      Assert.assertEquals("wrong bPK", bpk,  +      Assert.assertEquals("wrong bPK", bpk,            authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.BPK_NAME));    } -   +    @Test    public void buildDummyIdl() throws Exception {      //initialize test      String randomTestSp = RandomStringUtils.randomAlphabetic(10);      pendingReq.setRawDataToTransaction(MsEidasNodeConstants.DATA_REQUESTERID, randomTestSp); -        +      basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "true"); -     -     + +      //perform test      task.execute(pendingReq, executionContext); -     -    //validate state     + +    //validate state      // check if pendingRequest was stored      IRequest storedPendingReq = requestStorage.getPendingRequest(pendingReq.getPendingRequestId());      Assert.assertNotNull("pendingReq not stored", storedPendingReq); -     +      //check data in session      final AuthProcessDataWrapper authProcessData = storedPendingReq.getSessionData(AuthProcessDataWrapper.class);      Assert.assertNotNull("AuthProcessData", authProcessData); @@ -404,17 +472,14 @@ public class CreateIdentityLinkTaskTest {      String authBlock = authProcessData.getGenericDataFromSession(Constants.SZR_AUTHBLOCK, String.class);      Assert.assertNull("AuthBlock", authBlock); -     +      Assert.assertFalse("EID process", authProcessData.isEidProcess());      Assert.assertTrue("foreigner process", authProcessData.isForeigner()); -    Assert.assertEquals("EID-ISSUING_NATION", "LU",  +    Assert.assertEquals("EID-ISSUING_NATION", "LU",          authProcessData.getGenericDataFromSession(PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); -    Assert.assertNotNull("LoA is null", authProcessData.getQaaLevel()); -    Assert.assertEquals("LoA", response.getLevelOfAssurance(),  -        authProcessData.getQaaLevel()); -         +      Assert.assertNotNull("IDL", authProcessData.getIdentityLink()); -         +    }    private void setSzrResponseIdentityLink(String responseXmlPath) throws JAXBException, SZRException_Exception { @@ -433,7 +498,7 @@ public class CreateIdentityLinkTaskTest {      Assert.assertEquals(expected, value);    } -   +    @NotNull    private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException {      final AttributeDefinition attributeDef = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( @@ -444,7 +509,7 @@ public class CreateIdentityLinkTaskTest {          Constants.eIDAS_ATTR_CURRENTGIVENNAME).first();      final AttributeDefinition attributeDef4 = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(          Constants.eIDAS_ATTR_DATEOFBIRTH).first(); -    +      final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder()          .put(attributeDef, "LU/AT/" + RandomStringUtils.randomNumeric(64))          .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) @@ -461,4 +526,54 @@ public class CreateIdentityLinkTaskTest {          .attributes(attributeMap)          .build();    } +   +  private Map<String, Object> convertEidasAttrToSimpleMap( +      ImmutableMap<AttributeDefinition<?>, ImmutableSet<? extends AttributeValue<?>>> attributeMap) { +    final Map<String, Object> result = new HashMap<>(); +    for (final AttributeDefinition<?> el : attributeMap.keySet()) { +      final Class<?> parameterizedType = el.getParameterizedType(); +      if (DateTime.class.equals(parameterizedType)) { +        convertDateTime(attributeMap, result, el); +      } else if (PostalAddress.class.equals(parameterizedType)) { +        convertPostalAddress(attributeMap, result, el); +      } else { +        convertString(attributeMap, result, el); +      } +    } +    return result; +  } + +  private void convertString(ImmutableMap<AttributeDefinition<?>, +                             ImmutableSet<? extends AttributeValue<?>>> attributeMap, +                             Map<String, Object> result, AttributeDefinition<?> el) { +    final List<String> natPersonIdObj = EidasResponseUtils +        .translateStringListAttribute(el, attributeMap.get(el)); +    final String stringAttr = natPersonIdObj.get(0); +    if (StringUtils.isNotEmpty(stringAttr)) { +      result.put(el.getFriendlyName(), stringAttr); + +    } +  } + +  private void convertPostalAddress(ImmutableMap<AttributeDefinition<?>, +                                    ImmutableSet<? extends AttributeValue<?>>> attributeMap, +                                    Map<String, Object> result, AttributeDefinition<?> el) { +    final PostalAddress addressAttribute = EidasResponseUtils +        .translateAddressAttribute(el, attributeMap.get(el).asList()); +    if (addressAttribute != null) { +      result.put(el.getFriendlyName(), addressAttribute); + +    } +  } + +  private void convertDateTime(ImmutableMap<AttributeDefinition<?>, +                               ImmutableSet<? extends AttributeValue<?>>> attributeMap, +                               Map<String, Object> result, AttributeDefinition<?> el) { +    final DateTime attribute = EidasResponseUtils.translateDateAttribute(el, attributeMap.get(el).asList()); +    if (attribute != null) { +      result.put(el.getFriendlyName(), attribute); + +    } +  } +    } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateMobilePhoneSignatureRequestTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateMobilePhoneSignatureRequestTaskTest.java new file mode 100644 index 00000000..8e5ecfe1 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateMobilePhoneSignatureRequestTaskTest.java @@ -0,0 +1,279 @@ +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.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateMobilePhoneSignatureRequestTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.module.gui.DummyGuiBuilderConfigurationFactory; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SamlVerificationEngine; +import 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.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.common.xml.SAMLConstants; +import org.opensaml.saml.saml2.core.AuthnRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +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 java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Base64; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.springframework.util.Assert.isInstanceOf; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml", +    "classpath:/eaaf_pvp_sp.beans.xml" +}) + +public class GenerateMobilePhoneSignatureRequestTaskTest { + +  private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; +  private static final String METADATA_SP_PATH = "classpath:/data/sp_metadata_junit.xml"; + +  @Autowired(required = true) +  private ApplicationContext context; +  @Autowired(required = true) +  protected MsConnectorDummyConfigMap authConfig; +  @Autowired +  private IdAustriaClientAuthMetadataProvider metadataProvider; +  @Autowired +  private PvpMetadataResolverFactory metadataFactory; +  @Autowired +  private DummyGuiBuilderConfigurationFactory guiBuilderConfigFactory; +  @Autowired +  private SamlVerificationEngine samlVerifyEngine; +  @Autowired +  private ITransactionStorage transactionStorage; + +  final ExecutionContext executionContext = new ExecutionContextImpl(); +  private MockHttpServletRequest httpReq; +  private MockHttpServletResponse httpResp; +  private TestRequestImpl pendingReq; +  private DummyOA oaParam; + +  private GenerateMobilePhoneSignatureRequestTask task; + +  /** +   * 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 { +    task = (GenerateMobilePhoneSignatureRequestTask) context.getBean( +        "GenerateMobilePhoneSignatureRequestTask"); + +    httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); +    httpResp = new MockHttpServletResponse(); +    RequestContextHolder.resetRequestAttributes(); +    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + +    authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, +        METADATA_PATH); +    authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS, +        "sig"); + +    oaParam = new DummyOA(); +    oaParam.setUniqueAppId("http://test.com/test"); +    oaParam.setBmiUniqueIdentifier(oaParam.getUniqueIdentifier() + "#" + RandomStringUtils.randomAlphanumeric( +        5)); +    oaParam.setTargetIdentifier( +        EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); +    oaParam.setEidasEnabled(true); + +    pendingReq = new TestRequestImpl(); +    pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); +    pendingReq.setSpConfig(oaParam); +    pendingReq.setAuthUrl("https://localhost/authhandler"); + +    metadataProvider.fullyDestroy(); +    guiBuilderConfigFactory.setVelocityBuilderConfig(createDummyGuiConfig()); + +  } + +  @Test +  public void noMetadataAvailableOnGlobalConfig() { +    authConfig.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID); + +    final TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    assertNotNull(e.getOriginalException()); +    isInstanceOf(EaafConfigurationException.class, e.getOriginalException()); +    assertEquals("module.eidasauth.00", ((EaafConfigurationException) e.getOriginalException()).getErrorId()); +  } + +  @Test +  public void wrongMetadataAvailableOnGlobalConfig() { +    authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, +        "http://wrong.path/" + RandomStringUtils.randomAlphabetic(5)); + +    final TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); +    assertNotNull(e.getPendingRequestID()); +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    assertNotNull(e.getOriginalException()); +    isInstanceOf(EaafConfigurationException.class, e.getOriginalException()); +    assertEquals("module.eidasauth.idaustria.02", +        ((EaafConfigurationException) e.getOriginalException()).getErrorId()); +  } + +  @Test +  public void noMetadataSigningKeyStore() throws Pvp2MetadataException { +    authConfig.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS); + +    metadataProvider.addMetadataResolverIntoChain( +        metadataFactory.createMetadataProvider(METADATA_PATH, null, "jUnitTest", null)); + +    final TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); +    assertNotNull(e.getPendingRequestID()); +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    assertNotNull(e.getOriginalException()); +    isInstanceOf(CredentialsNotAvailableException.class, e.getOriginalException()); +    assertEquals("internal.pvp.01", +        ((CredentialsNotAvailableException) e.getOriginalException()).getErrorId()); +  } + +  @Test +  public void success() throws Exception { +    metadataProvider.addMetadataResolverIntoChain( +        metadataFactory.createMetadataProvider(METADATA_PATH, null, "jUnitTest", null)); +    pendingReq.setTransactionId(RandomStringUtils.randomAlphanumeric(10)); + +    task.execute(pendingReq, executionContext); + +    validate(); + +  } + +  private void validate() throws Exception { +    assertEquals("HTTP Statuscode", 200, httpResp.getStatus()); +    assertEquals("ContentType", "text/html;charset=UTF-8", httpResp.getContentType()); +    assertEquals("ContentEncoding", "UTF-8", httpResp.getCharacterEncoding()); + +    final String html = httpResp.getContentAsString(); +    assertNotNull("XML Metadata", html); + +    final int startIndex = html.indexOf("SAMLRequest="); +    assertTrue("No SAMLRequest in html", startIndex >= 0); +    final String authnXml = html.substring(startIndex + "SAMLRequest=".length()); + +    // check if relaystate was stored +    final int startIndexRelayState = html.indexOf("RelayState="); +    assertTrue("wrong RelayState in HTML", +        startIndexRelayState >= 0); +    final String relayState = html.substring(startIndexRelayState + "RelayState=".length(), startIndex); +    final String storedPendingReqId = transactionStorage.get(relayState, String.class); +    assertEquals("relayStore not map to pendingRequestId", +        pendingReq.getPendingRequestId(), storedPendingReqId); + +    final AuthnRequest authnRequest = (AuthnRequest) XMLObjectSupport.unmarshallFromInputStream( +        XMLObjectProviderRegistrySupport.getParserPool(), new ByteArrayInputStream( +            Base64.getDecoder().decode(authnXml))); + +    assertNotNull("AuthnReq", authnRequest); +    assertNotNull("Issuer", authnRequest.getIssuer()); +    assertEquals("EntityId", +        "https://localhost/authhandler" + IdAustriaClientAuthConstants.ENDPOINT_METADATA, +        authnRequest.getIssuer().getValue()); + +    // check XML scheme +    Saml2Utils.schemeValidation(authnRequest); + +    // check signature +    final PvpSProfileRequest msg = new PvpSProfileRequest( +        authnRequest, +        SAMLConstants.SAML2_POST_BINDING_URI); +    msg.setEntityID(authnRequest.getIssuer().getValue()); +    metadataProvider.addMetadataResolverIntoChain( +        metadataFactory.createMetadataProvider(METADATA_SP_PATH, null, "jUnit SP", null)); +    samlVerifyEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); + +    assertNotNull("RequestedAuthnContext", authnRequest.getRequestedAuthnContext()); +    assertNotNull("AuthnContextClassRef", authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs()); +    assertEquals("#AuthnContextClassRef", 1, +        authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().size()); +    assertEquals("LoA", "http://eidas.europa.eu/LoA/high", +        authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef()); + +  } + +  private IVelocityGuiBuilderConfiguration createDummyGuiConfig() { +    return new IVelocityGuiBuilderConfiguration() { + +      @Override +      public Map<String, Object> getViewParameters() { +        return null; +      } + +      @Override +      public String getViewName() { +        return "SAML2 Post-Binding"; +      } + +      @Override +      public String getDefaultContentType() { +        return null; +      } + +      @Override +      public InputStream getTemplate(String viewName) { +        return GenerateMobilePhoneSignatureRequestTaskTest.class.getResourceAsStream( +            "/data/pvp_postbinding_template.html"); +      } + +      @Override +      public String getClasspathTemplateDir() { +        return null; + +      } +    }; +  } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateOtherLoginMethodGuiTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateOtherLoginMethodGuiTaskTest.java new file mode 100644 index 00000000..0b169ca4 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateOtherLoginMethodGuiTaskTest.java @@ -0,0 +1,143 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import java.io.UnsupportedEncodingException; +import java.text.MessageFormat; +import java.util.Locale; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +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 at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SelectedLoginMethod; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateOtherLoginMethodGuiTask; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml", +    "/common_gui.beans.xml" +}) +@WebAppConfiguration +public class GenerateOtherLoginMethodGuiTaskTest { + +  private static final String TEST_PATTER_REQ_PARAM =  +      "<input type=\"hidden\" name=\"loginSelection\" value=\"{0}\">"; +   +  @Autowired GenerateOtherLoginMethodGuiTask task; +   +  private ExecutionContextImpl executionContext = new ExecutionContextImpl(); +  private TestRequestImpl pendingReq; +  private MockHttpServletRequest httpReq; +  private MockHttpServletResponse httpResp; +   +  /** +   * jUnit test set-up. +   *  +   */ +  @Before +  public void initialize() { +    httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); +    httpResp = new MockHttpServletResponse(); +    RequestContextHolder.resetRequestAttributes(); +    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); +     +    pendingReq = new TestRequestImpl(); +    pendingReq.setAuthUrl("https://localhost/ms_connector"); +    pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); +     +    LocaleContextHolder.resetLocaleContext(); +  } +   +  @Test +  public void validHtmlResponseWithOutLocale() throws TaskExecutionException, UnsupportedEncodingException {     +     +    task.execute(pendingReq, executionContext); +     +    //result validation +    String html = doBasicValidation(); +     +    Assert.assertTrue("No english text",  +        html.contains("Information on Logins with European eIDs")); +     +  } +   +  @Test +  public void validHtmlResponseWithDE() throws TaskExecutionException, UnsupportedEncodingException {     +    LocaleContextHolder.setLocale(Locale.GERMAN); +    httpReq.addHeader("Accept-Language", "de"); +     +    task.execute(pendingReq, executionContext); +     +    //result validation +    String html = doBasicValidation(); +     +    Assert.assertTrue("No english text",  +        html.contains("Information zur Anmeldung über Europäische eIDs")); +     +  } +   +  @Test +  public void validHtmlResponseWithEN() throws TaskExecutionException, UnsupportedEncodingException {     +    LocaleContextHolder.setLocale(Locale.ENGLISH); +     +    task.execute(pendingReq, executionContext); +     +    //result validation +    String html = doBasicValidation(); +     +    Assert.assertTrue("No english text",  +        html.contains("Information on Logins with European eIDs")); +     +  } +   +  @Test +  public void validHtmlResponseWithFR() throws TaskExecutionException, UnsupportedEncodingException {     +    LocaleContextHolder.setLocale(Locale.FRANCE); +    httpReq.addHeader("Accept-Language", "fr"); +     +    task.execute(pendingReq, executionContext); +     +    //result validation +    String html = doBasicValidation(); +     +    Assert.assertTrue("No english text",  +        html.contains("Information on Logins with European eIDs")); +     +  } +   +  private String doBasicValidation() throws UnsupportedEncodingException { +    Assert.assertEquals("Wrong http StatusCode", 200, httpResp.getStatus()); +    Assert.assertEquals("Wrong http ContentType", "text/html;charset=UTF-8", httpResp.getContentType()); +     +    String html = httpResp.getContentAsString(); +    Assert.assertNotNull("html result is null", html); +    Assert.assertFalse("html result is empty", html.isEmpty());     +     +    Assert.assertTrue("Missing IDA Login",  +        html.contains(MessageFormat.format(TEST_PATTER_REQ_PARAM, SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN))); +    Assert.assertTrue("Missing residence infos",  +        html.contains(MessageFormat.format(TEST_PATTER_REQ_PARAM, SelectedLoginMethod.NO_OTHER_LOGIN))); +         +    Assert.assertTrue("No language selector with pendingRequestId",  +        html.contains("/otherLoginMethod?pendingid=" + pendingReq.getPendingRequestId())); +    Assert.assertTrue("No country-selection form",  +        html.contains("<form class=\"block\" method=\"post\" action=\"/otherLoginMethod\">")); +         +    return html; +     +  } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskTest.java new file mode 100644 index 00000000..b0de3460 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskTest.java @@ -0,0 +1,731 @@ +/* + * Copyright 2020 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.test.tasks; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.clients.zmr.IZmrClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.clients.zmr.ZmrSoapClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.clients.zmr.ZmrSoapClient.ZmrRegisterResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MatchedPersonResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.RegisterResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.*; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.CountrySpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.GenericEidProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.ICcSpecificEidProcessingService; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService.RegisterStatusResults; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.MatchingTaskUtils; +import at.gv.bmi.namespace.zmr_su.zmr._20040201.PersonSuchenRequest; +import at.gv.egiz.eaaf.core.api.IRequest; +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.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; +import eu.eidas.auth.commons.attribute.PersonType; +import eu.eidas.auth.commons.light.impl.LightRequest; +import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +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.annotation.DirtiesContext.ClassMode; +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.namespace.QName; +import java.math.BigInteger; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) +public class InitialSearchTaskTest { + + +  private static final String EE = "EE"; +  private static final String DE = "DE"; + +  private static final String EE_ST = EE + "/ST/"; +  private static final String DE_ST = DE + "/ST/"; + +  @Mock +  private IZmrClient zmrClient; +  @Mock +  private IErnpClient ernpClient; + +  @Autowired +  private List<CountrySpecificDetailSearchProcessor> handlers; +  private RegisterSearchService registerSearchService; + +  private final ICcSpecificEidProcessingService eidPostProcessor = createEidPostProcessor(); +  private InitialSearchTask task; + +  final ExecutionContext executionContext = new ExecutionContextImpl(); +  private TestRequestImpl pendingReq; +  private final String randomBpk = RandomStringUtils.randomNumeric(6); +  private final String randomPseudonym = RandomStringUtils.randomNumeric(10); +  private final String randomPersonalIdentifier_DE = DE_ST + randomPseudonym; +  private final String randomPersonalIdentifier_EE = EE_ST + randomPseudonym; +  private final String randomFamilyName = randomAlphabetic(10); +  private final String randomGivenName = randomAlphabetic(10); +  private final String randomPlaceOfBirth = randomAlphabetic(10); +  private final String randomBirthName = randomAlphabetic(10); +  private final String randomBirthDate = "2011-01-" + (10 + new Random().nextInt(18)); + +  /** +   * jUnit test set-up. +   */ +  @Before +  public void setUp() throws URISyntaxException, EaafStorageException { +    MockitoAnnotations.initMocks(this); + +    registerSearchService = new RegisterSearchService(handlers, zmrClient, ernpClient); +    task = new InitialSearchTask(registerSearchService, eidPostProcessor); + +    MockHttpServletRequest httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); +    MockHttpServletResponse httpResp = new MockHttpServletResponse(); +    RequestContextHolder.resetRequestAttributes(); +    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + +    final AuthenticationResponse response = buildDummyAuthResponseRandomPerson(); +    pendingReq = new TestRequestImpl(); +    pendingReq.getSessionData(AuthProcessDataWrapper.class) +        .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); +  } + +  @NotNull +  private ICcSpecificEidProcessingService createEidPostProcessor() { +    return new ICcSpecificEidProcessingService() { + +      private final GenericEidProcessor genericEidProcessor = new GenericEidProcessor(); + +      @Override +      public SimpleEidasData postProcess(Map<String, Object> eidasAttrMap) throws EidPostProcessingException, EidasAttributeException { +        return genericEidProcessor.postProcess(eidasAttrMap); +      } + +      @Override +      public void preProcess(String selectedCC, IRequest pendingReq, LightRequest.Builder authnRequestBuilder) { +        genericEidProcessor.preProcess(pendingReq, authnRequestBuilder); +      } +    }; +  } + +  /** +   * One match, but register update needed +   */ +  @Test +  @DirtiesContext +  public void singlePersonalIdMatchUpdateNecessary_Zmr() throws Exception { +    String oldGivenName = randomAlphabetic(10); +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(zmrRegisterResult(randomRegisterResult(oldGivenName, randomBpk))); + +    Mockito.when(zmrClient.searchCountrySpecific(any(), any(), any())) +        .thenThrow(new IllegalStateException("CountrySpecific search search should not be neccessary")); +    Mockito.when(zmrClient.searchWithMds(any(), any(), any(), any(), any())) +        .thenThrow(new IllegalStateException("MDS search should not be neccessary")); +    Mockito.when(zmrClient.update(any(), any(), any())) +        .thenThrow(new IllegalStateException("ZMR update should not be neccessary")); + +    // execute test +    task.execute(pendingReq, executionContext); + +    // validate state +    //INFO: has to be the old givenName because ZMR allows no update of MDS information +    checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, oldGivenName, randomBirthDate, DE); + +  } + +  /** +   * TODO: include again if ERnP update is implementet. Maybe we can update MDS based on ERnP. +   * <p> +   * One match, but register update needed. +   * +   * @throws EidasSAuthenticationException +   */ +  @Ignore +  @Test +  @DirtiesContext +  public void singlePersonalIdMatchUpdateNecessary_Ernp() throws TaskExecutionException, EidasSAuthenticationException { +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(emptyZmrRegisterResult()); + +    String oldRandomGivenName = randomAlphabetic(10); +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.singletonList(randomRegisterResult(oldRandomGivenName, randomBpk))); + +    // execute test +    task.execute(pendingReq, executionContext); + +    // validate state +    checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); +  } + +  @NotNull +  private ZmrSoapClient.ZmrRegisterResult emptyZmrRegisterResult() { +    return new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId()); +  } + +  /** +   * Two matches by PersonalId found in ZMR +   * +   * @throws EidasSAuthenticationException +   */ +  @Test +  @DirtiesContext +  public void multiPersonalIdMatch_Zmr() throws EidasSAuthenticationException { +    String newRandomGivenName = randomAlphabetic(10); +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(new ZmrRegisterResult(Arrays.asList(randomRegisterResult(), randomRegisterResult(newRandomGivenName, randomBpk)), generateRandomProcessId())); +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.emptyList()); + +    // execute task +    TaskExecutionException exception = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + + +    // validate state +    assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); +    assertTrue("Wrong flag 'manualFixNeeded'", +        ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + +  } + +  /** +   * Two matches by PersonalId found in ZMR +   * +   * @throws EidasSAuthenticationException +   */ +  @Test +  @DirtiesContext +  public void withErrorFromZmr() throws EidasSAuthenticationException { +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenThrow(new ZmrCommunicationException("jUnit ZMR error", null)); +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.emptyList()); + +    // execute task +    TaskExecutionException exception = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + + +    // validate state +    assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); +    assertFalse("Wrong flag 'manualFixNeeded'", +        ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + +  } + +  /** +   * Two matches by PersonalId found in ErnP +   * +   * @throws EidasSAuthenticationException +   */ +  @Test +  @DirtiesContext +  public void multiPersonalIdMatch_Ernp() throws EidasSAuthenticationException { +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(emptyZmrRegisterResult()); +    String newRandomGivenName = randomAlphabetic(10); +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Arrays.asList(randomRegisterResult(), randomRegisterResult(newRandomGivenName, randomBpk))); + +    // execute task +    TaskExecutionException exception = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    // validate state +    assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); +    assertTrue("Wrong flag 'manualFixNeeded'", +        ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + +  } + +  /** +   * Two matches by PersonalId +   * +   * @throws EidasSAuthenticationException +   */ +  @Test +  @DirtiesContext +  public void multiPersonalIdMatch_ErnpAndZmr() throws EidasSAuthenticationException { +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(zmrRegisterResult(randomRegisterResult())); +    String newRandomGivenName = randomAlphabetic(10); +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.singletonList(randomRegisterResult())); + +    // execute task +    TaskExecutionException exception = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    // validate state +    assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); +    assertTrue("Wrong flag 'manualFixNeeded'", +        ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + +  } + +  /** +   * One match by PersonalId, no register update needed +   */ +  @Test +  @DirtiesContext +  public void singlePersonalIdMatchNoUpdate_Ernp() throws Exception { +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(emptyZmrRegisterResult()); +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.singletonList(randomRegisterResult())); + +    // execute test +    task.execute(pendingReq, executionContext); + +    // validate state +    checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); +  } + +  /** +   * One match by PersonalId, no register update needed +   */ +  @Test +  @DirtiesContext +  public void singlePersonalIdMatchNoUpdate_Zmr() throws Exception { +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(zmrRegisterResult(randomRegisterResult())); +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.emptyList()); +    Mockito.when(zmrClient.update(any(), any(), any())) +        .thenThrow(new IllegalStateException("ZMR update should not be neccessary")); + +    // execute test +    task.execute(pendingReq, executionContext); + +    // validate state +    checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); +  } + +  /** +   * Find single person in ZMR by country specifics. +   */ +  @Test +  @DirtiesContext +  public void singlePersonFindWithCountySpecifics_Zmr() throws Exception { +    final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, +        randomPersonalIdentifier_DE, randomBirthDate, randomPlaceOfBirth, randomBirthName); +    TestRequestImpl pendingReq1 = new TestRequestImpl(); +    pendingReq1.getSessionData(AuthProcessDataWrapper.class) +        .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + +    BigInteger zmrProcessId = generateRandomProcessId(); +    RegisterResult zmrResult = RegisterResult.builder() +        .bpk(randomBpk) +        .pseudonym(Collections.singletonList(randomPseudonym)) +        .givenName(randomGivenName) +        .familyName(randomFamilyName) +        .dateOfBirth(randomBirthDate) +        .placeOfBirth(randomPlaceOfBirth) +        .birthName(randomBirthName) +        .build(); +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))) +        .thenReturn(zmrRegisterResult(zmrResult, zmrProcessId)); +    RegisterResult randomRegisterResult = RegisterResult.builder() +        .bpk(randomBpk) +        .pseudonym(Arrays.asList(randomPseudonym, RandomStringUtils.randomAlphanumeric(10))) +        .givenName(randomGivenName) +        .familyName(randomFamilyName) +        .dateOfBirth(randomBirthDate) +        .placeOfBirth(randomPlaceOfBirth) +        .birthName(randomBirthName) +        .build(); +    Mockito.when(zmrClient.update(eq(zmrProcessId), eq(zmrResult), any())) +        .thenReturn(zmrRegisterResult(randomRegisterResult, zmrProcessId)); +    Mockito.when(zmrClient.searchWithMds(any(), any(), any(), any(), any())) +        .thenThrow(new IllegalStateException("MDS search should not be neccessary")); + +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.emptyList()); + +    // execute test +    task.execute(pendingReq1, executionContext); + +    // validate state +    checkMatchingSuccessState(pendingReq1, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); + +  } + +  /** +   * Multiple matches found in ZMR by country specifics. +   */ +  @Test +  @DirtiesContext +  public void multiplePersonFindWithCountySpecifics_Zmr() throws Exception { +    String newRandomPseudonym = randomPersonalIdentifier_DE + RandomStringUtils.randomNumeric(2); +    String newRandomBpk = randomBpk + RandomStringUtils.randomNumeric(6); +    final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, +        randomPersonalIdentifier_DE, +        randomBirthDate, randomPlaceOfBirth, randomBirthName); +    TestRequestImpl pendingReq1 = new TestRequestImpl(); +    pendingReq1.getSessionData(AuthProcessDataWrapper.class) +        .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + +    BigInteger zmrProcessId = generateRandomProcessId(); +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    RegisterResult randomResult1 = RegisterResult.builder() +        .bpk(randomBpk) +        .pseudonym(Collections.singletonList(randomPseudonym)) +        .givenName(randomGivenName) +        .familyName(randomFamilyName) +        .dateOfBirth(randomBirthDate) +        .placeOfBirth(randomPlaceOfBirth) +        .birthName(randomBirthName) +        .build(); +    RegisterResult randomResult2 = RegisterResult.builder() +        .bpk(newRandomBpk) +        .pseudonym(Collections.singletonList(newRandomPseudonym)) +        .givenName(randomGivenName) +        .familyName(randomFamilyName) +        .dateOfBirth(randomBirthDate) +        .placeOfBirth(randomPlaceOfBirth) +        .birthName(randomBirthName) +        .build(); +    Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))) +        .thenReturn(new ZmrRegisterResult(Arrays.asList(randomResult1, randomResult2), zmrProcessId)); + +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.emptyList()); + +    // execute task +    TaskExecutionException exception = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq1, executionContext)); + +    // validate state +    assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); +    assertTrue("Wrong flag 'manualFixNeeded'", +        ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + +  } + +  /** +   * NO match found in ZMR and ErnP with Initial and MDS search +   * +   * @throws EidasSAuthenticationException +   * @throws URISyntaxException +   * @throws EaafStorageException +   */ +  @Test +  @DirtiesContext +  public void noResultByAnySearch() throws TaskExecutionException, EidasSAuthenticationException, URISyntaxException, EaafStorageException { +    BigInteger zmrProcessId = generateRandomProcessId(); +    pendingReq.getSessionData(AuthProcessDataWrapper.class) +        .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, +            buildDummyAuthResponse(randomGivenName, randomFamilyName, randomPersonalIdentifier_EE, randomBirthDate)); + +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, EE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, EE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    Mockito.when(zmrClient.update(any(), any(), any())) +        .thenThrow(new IllegalStateException("ZMR update should not be neccessary")); + +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_EE)) +        .thenReturn(Collections.emptyList()); + + +    // execute task +    task.execute(pendingReq, executionContext); + + +    // validate state +    assertNotNull("find no eIDAS inbut data", MatchingTaskUtils.getInitialEidasData(pendingReq)); + +    assertNull("Find intermediate matching data but matching should be finished", +        MatchingTaskUtils.getIntermediateMatchingResult(pendingReq)); +    assertNull("Find final matching data but no match sould be found", +        MatchingTaskUtils.getFinalMatchingResult(pendingReq)); + +    Boolean transitionGUI = (Boolean) executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); +    Assert.assertNull("Wrong transition", transitionGUI); +    Boolean transitionErnb = (Boolean) executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK); +    Assert.assertTrue("Wrong transition", transitionErnb); + +  } + +  /** +   * Find one match with MDS search in ERnP. +   */ +  @Test +  @DirtiesContext +  public void resultByMdsSearch_Ernb() throws TaskExecutionException, EidasSAuthenticationException, URISyntaxException, EaafStorageException { +    BigInteger zmrProcessId = generateRandomProcessId(); +    pendingReq.getSessionData(AuthProcessDataWrapper.class) +        .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, +            buildDummyAuthResponse(randomGivenName, randomFamilyName, randomPersonalIdentifier_EE, randomBirthDate)); + +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, EE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, EE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); + +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_EE)) +        .thenReturn(Collections.emptyList()); +    Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)) +        .thenReturn(Collections.singletonList(randomRegisterResult())); + +    // execute test +    task.execute(pendingReq, executionContext); + +    // validate state +    checkIntermediateResult(1); + +  } + +  /** +   * Find one match with MDS search in ZMR. +   */ +  @Test +  @DirtiesContext +  public void resultByMdsSearch_Zmr() throws TaskExecutionException, EidasSAuthenticationException { +    BigInteger zmrProcessId = generateRandomProcessId(); +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, DE)) +        .thenReturn(zmrRegisterResult(randomRegisterResult(), zmrProcessId)); +    Mockito.when(zmrClient.update(any(), any(), any())) +        .thenThrow(new IllegalStateException("ZMR update should not be neccessary")); + +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + + +    // execute test +    task.execute(pendingReq, executionContext); + +    // validate state +    checkIntermediateResult(1); + +  } + +  /** +   * resultByMdsSearch +   */ +  @Test +  @DirtiesContext +  public void multipleResultsByMdsSearch() throws TaskExecutionException, EidasSAuthenticationException { +    BigInteger zmrProcessId = generateRandomProcessId(); +    Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), any(String.class))) +        .thenReturn(new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); +    Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, DE)) +        .thenReturn(zmrRegisterResult(randomRegisterResult(randomBpk + "2"), zmrProcessId)); +    Mockito.when(zmrClient.update(any(), any(), any())) +        .thenThrow(new IllegalStateException("ZMR update should not be neccessary")); + +    Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)) +        .thenReturn(Collections.emptyList()); +    Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)) +        .thenReturn(Arrays.asList(randomRegisterResult(), randomRegisterResult(randomBpk + "1"))); + +    // execute test +    task.execute(pendingReq, executionContext); + +    // validate state +    checkIntermediateResult(3); + +  } + +  @NotNull +  private ZmrRegisterResult zmrRegisterResult(RegisterResult registerResult, BigInteger processId) { +    return new ZmrRegisterResult(Collections.singletonList(registerResult), processId); +  } + +  @NotNull +  private ZmrRegisterResult zmrRegisterResult(RegisterResult registerResult) { +    return zmrRegisterResult(registerResult, generateRandomProcessId()); +  } + +  @NotNull +  private RegisterResult randomRegisterResult() { +    return randomRegisterResult(randomGivenName, randomBpk); +  } + +  @NotNull +  private RegisterResult randomRegisterResult(String randomBpk) { +    return randomRegisterResult(randomGivenName, randomBpk); +  } + +  @NotNull +  private RegisterResult randomRegisterResult(String randomGivenName, String randomBpk) { +    return RegisterResult.builder() +        .bpk(randomBpk) +        .pseudonym(Collections.singletonList(randomPseudonym)) +        .givenName(randomGivenName) +        .familyName(randomFamilyName) +        .dateOfBirth(randomBirthDate) +        .build(); +  } + +  @NotNull +  private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { +    return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomPseudonym, randomBirthDate); +  } + +  private BigInteger generateRandomProcessId() { +    return new BigInteger(RandomStringUtils.randomNumeric(10)); + +  } + +  private void checkMatchingSuccessState(IRequest pendingReq, String bpk, String familyName, String givenName, +                                         String birhday, String countryCode) { +    assertNull("Find intermediate matching data but matching should be finished", +        MatchingTaskUtils.getIntermediateMatchingResult(pendingReq)); +    assertNotNull("find no eIDAS inbut data", MatchingTaskUtils.getInitialEidasData(pendingReq)); + +    MatchedPersonResult personInfo = MatchingTaskUtils.getFinalMatchingResult(pendingReq); +    assertNotNull("no final matching result", personInfo); +    assertEquals("wrong bpk", bpk, personInfo.getBpk()); +    assertEquals("wrong givenName", givenName, personInfo.getGivenName()); +    assertEquals("wrong familyName", familyName, personInfo.getFamilyName()); +    assertEquals("wrong dateOfBirth", birhday, personInfo.getDateOfBirth()); +    assertEquals("wrong countryCode", countryCode, personInfo.getCountryCode()); + +  } + +  private void checkIntermediateResult(int resultSize) { +    Boolean transitionGUI = (Boolean) executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); +    Assert.assertTrue("Wrong transition", transitionGUI); +    Boolean transitionErnb = (Boolean) executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK); +    Assert.assertNull("Wrong transition", transitionErnb); + +    assertNotNull("find no eIDAS inbut data", MatchingTaskUtils.getInitialEidasData(pendingReq)); +    assertNull("Find final matching data but no match sould be found", +        MatchingTaskUtils.getFinalMatchingResult(pendingReq)); + +    RegisterStatusResults result = MatchingTaskUtils.getIntermediateMatchingResult(pendingReq); +    assertNotNull("Find no intermediate matching data", result); +    assertEquals("wrong intermediate result size", resultSize, result.getResultCount()); + +  } + +  @NotNull +  private AuthenticationResponse buildDummyAuthResponse(String givenName, String familyName, String identifier, +                                                        String dateOfBirth) throws URISyntaxException { +    return buildDummyAuthResponse(givenName, familyName, identifier, dateOfBirth, null, null, null); +  } + +  @NotNull +  private AuthenticationResponse buildDummyAuthResponseDE(String givenName, String familyName, String identifier, +                                                          String dateOfBirth, String placeOfBirth, +                                                          String birthName) throws URISyntaxException { +    return buildDummyAuthResponse(givenName, familyName, identifier, dateOfBirth, null, placeOfBirth, birthName); +  } + +  @NotNull +  private AuthenticationResponse buildDummyAuthResponse(String givenName, String familyName, String identifier, +                                                        String dateOfBirth, String taxNumber, String placeOfBirth, +                                                        String birthName) throws URISyntaxException { +    ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() +        .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER, +            randomAlphabetic(2), randomAlphabetic(2)), identifier) +        .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, +            randomAlphabetic(3), randomAlphabetic(3)), familyName) +        .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME, +            randomAlphabetic(4), randomAlphabetic(4)), givenName) +        .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH, +            randomAlphabetic(5), randomAlphabetic(5)), dateOfBirth); +    if (taxNumber != null) { +      builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE, +          randomAlphabetic(6), randomAlphabetic(6)), taxNumber); +    } +    if (birthName != null) { +      builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME, +          randomAlphabetic(7), randomAlphabetic(7)), birthName); +    } +    if (placeOfBirth != null) { +      builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH, +          randomAlphabetic(8), randomAlphabetic(8)), placeOfBirth); +    } +    final ImmutableAttributeMap attributeMap = builder.build(); + +    return new AuthenticationResponse.Builder().id(randomAlphabetic(5)) +        .issuer(randomAlphabetic(5)).subject(randomAlphabetic(5)).statusCode("200") +        .inResponseTo(randomAlphabetic(5)).subjectNameIdFormat(randomAlphabetic(5)) +        .attributes(attributeMap).build(); +  } + +  private AttributeDefinition<Object> generateStringAttribute(String friendlyName, String fragment, String prefix) +      throws URISyntaxException { +    return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + +        ".LiteralStringAttributeValueMarshaller"); +  } + +  @SuppressWarnings("SameParameterValue") +  private AttributeDefinition<Object> generateDateTimeAttribute(String friendlyName, String fragment, String prefix) +      throws URISyntaxException { +    return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + +        ".DateTimeAttributeValueMarshaller"); +  } + +  private AttributeDefinition<Object> generateAttribute(String friendlyName, String fragment, String prefix, +                                                        String marshaller) throws URISyntaxException { +    return AttributeDefinition.builder() +        .friendlyName(friendlyName).nameUri(new URI("ad", "sd", fragment)) +        .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", prefix)) +        .attributeValueMarshaller(marshaller).build(); +  } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAustrianResidenceGuiResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAustrianResidenceGuiResponseTaskTest.java new file mode 100644 index 00000000..25a77cce --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAustrianResidenceGuiResponseTaskTest.java @@ -0,0 +1,249 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask.PARAM_CITY; +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask.PARAM_FORMER_RESIDENCE_AVAILABLE; +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask.PARAM_STREET; +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask.PARAM_ZIPCODE; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.eq; +import static org.springframework.util.Assert.isInstanceOf; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.mock.mockito.MockBean; +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.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.google.common.collect.Lists; + +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.RegisterResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService.RegisterOperationStatus; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService.RegisterStatusResults; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask.UserInput; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.utils.MatchingTaskUtils; +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.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { +    "/SpringTest-context_tasks_test.xml", +    "/SpringTest-context_basic_mapConfig.xml" +}) +public class ReceiveAustrianResidenceGuiResponseTaskTest { + +  @Autowired +  protected MsConnectorDummyConfigMap authConfig; +      +  @MockBean +  private RegisterSearchService registerSearchService; + +  private ReceiveAustrianResidenceGuiResponseTask task; +   +  private final ExecutionContext executionContext = new ExecutionContextImpl(); +  private MockHttpServletRequest httpReq; +  private MockHttpServletResponse httpResp; +  private TestRequestImpl pendingReq; + +  /** +   * jUnit test set-up. +   * +   * @throws Exception In case of an set-up error +   */ +  @Before +  public void setUp() throws Exception { +    MockitoAnnotations.initMocks(this); + +    task = new ReceiveAustrianResidenceGuiResponseTask(registerSearchService); +     +    httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); +    httpResp = new MockHttpServletResponse(); +    RequestContextHolder.resetRequestAttributes(); +    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + +    pendingReq = new TestRequestImpl(); +    pendingReq.setAuthUrl("https://localhost/ms_connector"); +    pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); + +    LocaleContextHolder.resetLocaleContext(); +  } + +  @Test +  public void noRegisterResult() throws Exception { +    UserInput userInput = setupUserInput(); +    SimpleEidasData eidasData = setupEidasData(); +    RegisterStatusResults registerSearchResult = buildEmptyResult(); +    mockRegisterSearch(userInput, registerSearchResult, eidasData); +    MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); +     +    task.execute(pendingReq, executionContext); + +    assertEquals("Transition To S9", true, executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); +  } + +  @Test +  public void exactlyOneRegisterResult_Matching() throws Exception { +    UserInput userInput = setupUserInput(); +    SimpleEidasData eidasData = setupEidasData(); +    RegisterStatusResults registerSearchResult = buildResultWithOneMatch(buildMatchingRegisterResult(eidasData)); +    MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); +    mockRegisterSearch(userInput, registerSearchResult, eidasData); + +    task.execute(pendingReq, executionContext); + +    assertNull("Transition To S9", executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); +    Mockito.verify(registerSearchService).step7aKittProcess(eq(registerSearchResult), eq(eidasData)); +     +  } + +  @Test +  public void exactlyOneRegisterResult_NotMatching() throws Exception { +    UserInput userInput = setupUserInput(); +    SimpleEidasData eidasData = setupEidasData(); +    RegisterStatusResults registerSearchResult = buildResultWithOneMatch(buildNotMatchingRegisterResult(eidasData)); +    MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); +    mockRegisterSearch(userInput, registerSearchResult, eidasData); + +    task.execute(pendingReq, executionContext); + +    assertEquals("Transition To S9", true, executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); +  } + +  @Test +  public void moreThanOneRegisterResult() throws Exception { +    UserInput userInput = setupUserInput(); +    SimpleEidasData eidasData = setupEidasData(); +    RegisterStatusResults registerSearchResult = buildResultWithTwoMatches(); +    MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); +    mockRegisterSearch(userInput, registerSearchResult, eidasData); + +    TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    isInstanceOf(ManualFixNecessaryException.class, e.getOriginalException()); +    assertNull("Transition To S16", executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); +  } + +  private void mockRegisterSearch(UserInput userInput, RegisterStatusResults registerSearchResult, SimpleEidasData eidasData ) { +    Mockito.when(registerSearchService.searchWithResidence(eq(registerSearchResult.getOperationStatus()), eq(eidasData),  +        eq(userInput.getZipcode()), eq(userInput.getCity()), eq(userInput.getStreet()))).thenReturn(registerSearchResult); +  } + +  @NotNull +  private RegisterStatusResults buildEmptyResult() {     +    return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()),  +        Collections.emptyList(), Collections.emptyList()); +     +  } + +  private BigInteger generateRandomProcessId() { +    return new BigInteger(RandomStringUtils.randomNumeric(10)); +     +  } +   +  @NotNull +  private RegisterStatusResults buildResultWithOneMatch(RegisterResult registerResult) { +    return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()),  +        Collections.singletonList(registerResult), Collections.emptyList()); +     +  } + +  @NotNull +  private RegisterStatusResults buildResultWithTwoMatches() { +    List<RegisterResult> results = Lists.newArrayList(buildRandomRegisterResult(), buildRandomRegisterResult()); +    return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()),  +        results, Collections.emptyList()); +     +  } + +  @NotNull +  private RegisterResult buildRandomRegisterResult() { +    return RegisterResult.builder() +            .pseudonym(Arrays.asList(RandomStringUtils.randomAlphabetic(8))) +            .givenName(RandomStringUtils.randomAlphabetic(8)) +            .familyName(RandomStringUtils.randomAlphabetic(8)) +            .dateOfBirth(RandomStringUtils.randomAlphabetic(8)) +            .bpk(RandomStringUtils.randomAlphabetic(8)) +            .build();  +     +  } + +  private RegisterResult buildMatchingRegisterResult(SimpleEidasData eidData) { +    return RegisterResult.builder() +        .pseudonym(Arrays.asList(eidData.getPseudonym())) +        .givenName(eidData.getGivenName()) +        .familyName(eidData.getFamilyName()) +        .dateOfBirth(eidData.getDateOfBirth()) +        .bpk(RandomStringUtils.randomAlphabetic(8)) +        .build();  +        +  } + +  private RegisterResult buildNotMatchingRegisterResult(SimpleEidasData eidData) { +    return RegisterResult.builder() +        .pseudonym(Arrays.asList(eidData.getPseudonym() + RandomStringUtils.randomAlphabetic(8))) +        .givenName(eidData.getGivenName()) +        .familyName(eidData.getFamilyName()) +        .dateOfBirth(eidData.getDateOfBirth()) +        .bpk(RandomStringUtils.randomAlphabetic(8)) +        .build(); +     +  } + +  private void setHttpParameters(UserInput input) { +    httpReq.setParameter(PARAM_FORMER_RESIDENCE_AVAILABLE, String.valueOf(input.isFormerResidenceAvailable())); +    httpReq.setParameter(PARAM_STREET, input.getStreet()); +    httpReq.setParameter(PARAM_CITY, input.getCity()); +    httpReq.setParameter(PARAM_ZIPCODE, input.getZipcode()); +  } + +  @NotNull +  private SimpleEidasData setupEidasData() throws EaafStorageException { +    SimpleEidasData result = SimpleEidasData.builder() +        .pseudonym(RandomStringUtils.randomAlphabetic(8)) +        .familyName(RandomStringUtils.randomAlphabetic(8)) +        .givenName(RandomStringUtils.randomAlphabetic(8)) +        .dateOfBirth("1970-01-01") +        .build(); +    AuthProcessDataWrapper authProcessDataWrapper = pendingReq.getSessionData(AuthProcessDataWrapper.class); +    authProcessDataWrapper.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, result); +    return result; +  } + +  @NotNull +  private UserInput setupUserInput() { +    UserInput result = new UserInput(true, RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8)); +    setHttpParameters(result); +    return result; +  } + + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveEidasResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAuthnResponseTaskTest.java index 0e56e2b3..ea2cda4b 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveEidasResponseTaskTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAuthnResponseTaskTest.java @@ -13,7 +13,6 @@ import org.junit.Assert;  import org.junit.Before;  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; @@ -28,7 +27,6 @@ import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyCo  import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummySpConfiguration;  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.tasks.ReceiveAuthnResponseTask;  import at.gv.egiz.eaaf.core.api.IRequest;  import at.gv.egiz.eaaf.core.api.IRequestStorage; @@ -49,12 +47,11 @@ import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse;  import lombok.val;  @RunWith(SpringJUnit4ClassRunner.class) -@PrepareForTest(CreateIdentityLinkTask.class)  @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml",      "/SpringTest-context_basic_mapConfig.xml"}) -public class ReceiveEidasResponseTaskTest { +public class ReceiveAuthnResponseTaskTest {    @Autowired(required = true)    private ReceiveAuthnResponseTask task; @@ -63,15 +60,15 @@ public class ReceiveEidasResponseTaskTest {    private MsConnectorDummyConfigMap basicConfig;    @Autowired    protected EidasAttributeRegistry attrRegistry; -   +    @Autowired private IRequestStorage storage; -   +    final ExecutionContext executionContext = new ExecutionContextImpl();    private MockHttpServletRequest httpReq;    private MockHttpServletResponse httpResp;    private TestRequestImpl pendingReq;    private MsConnectorDummySpConfiguration oaParam; -   +    /**     * jUnit test set-up.     */ @@ -99,67 +96,67 @@ public class ReceiveEidasResponseTaskTest {      pendingReq.setAuthUrl("http://test.com/");      pendingReq.setTransactionId("avaasbav");      pendingReq.setPiiTransactionId(RandomStringUtils.randomAlphanumeric(10)); -         +      executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "LU");      executionContext.put(EaafConstants.PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT, true);    } -   +    @Test -  public void missingEidasResponse() {     +  public void missingEidasResponse() {      try {        task.execute(pendingReq, executionContext);        Assert.fail("No eIDAS response not detected"); -       +      } catch (TaskExecutionException e) { -      Assert.assertEquals("ErrorId", "eidas.01",  +      Assert.assertEquals("ErrorId", "eidas.01",            ((EaafException) e.getOriginalException()).getErrorId()); -       -    }         + +    }    } -   +    @Test -  public void notSuccessEidasResponse() throws URISyntaxException {     +  public void notSuccessEidasResponse() throws URISyntaxException {      String statusCode = RandomStringUtils.randomAlphabetic(10); -    httpReq.setAttribute(Constants.DATA_FULL_EIDAS_RESPONSE,  +    httpReq.setAttribute(Constants.DATA_FULL_EIDAS_RESPONSE,          buildDummyAuthResponse(statusCode)); -     -     + +      try {        task.execute(pendingReq, executionContext);        Assert.fail("No eIDAS response not detected"); -       +      } catch (TaskExecutionException e) { -      Assert.assertEquals("ErrorId", "eidas.02",  +      Assert.assertEquals("ErrorId", "eidas.02",            ((EaafException) e.getOriginalException()).getErrorId());        Assert.assertEquals("wrong parameter size", 2, ((EaafException) e.getOriginalException())            .getParams().length);        Assert.assertEquals("wrong errorMsg", statusCode, ((EaafException) e            .getOriginalException()).getParams()[0]); -    }         +    }    } -     +    @Test -  public void success() throws URISyntaxException, TaskExecutionException, PendingReqIdValidationException {     +  public void success() throws URISyntaxException, TaskExecutionException, PendingReqIdValidationException {      @NotNull      AuthenticationResponse eidasResponse = buildDummyAuthResponse(Constants.SUCCESS_URI);      httpReq.setAttribute(Constants.DATA_FULL_EIDAS_RESPONSE, eidasResponse); -    executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "LU");     -       +    executionContext.put(MsEidasNodeConstants.REQ_PARAM_SELECTED_COUNTRY, "LU"); +      //execute test      task.execute(pendingReq, executionContext); -     +      //validate state      IRequest storedReq = storage.getPendingRequest(pendingReq.getPendingRequestId());      Assert.assertNotNull("pendingReq not stored", storedReq); -          final EidAuthProcessDataWrapper authProcessData = storedReq.getSessionData(EidAuthProcessDataWrapper.class);      Assert.assertEquals("LoA", eidasResponse.getLevelOfAssurance(), authProcessData.getQaaLevel()); -    Assert.assertNotNull("eIDAS response",  +    Assert.assertNotNull("eIDAS response",          authProcessData.getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE)); -    Assert.assertEquals("eIDAS response", eidasResponse,  +    Assert.assertEquals("eIDAS response", eidasResponse,          authProcessData.getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE)); +          Assert.assertFalse("testIdentity flag", authProcessData.isTestIdentity());    } @@ -202,7 +199,7 @@ public class ReceiveEidasResponseTaskTest {          Constants.eIDAS_ATTR_CURRENTGIVENNAME).first();      final AttributeDefinition attributeDef4 = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(          Constants.eIDAS_ATTR_DATEOFBIRTH).first(); -    +      final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder()          .put(attributeDef, "LU/AT/" + RandomStringUtils.randomNumeric(64))          .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) @@ -219,5 +216,5 @@ public class ReceiveEidasResponseTaskTest {          .attributes(attributeMap)          .build();    } -   +  } 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..b072b8b2 --- /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,480 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.springframework.util.Assert.isInstanceOf; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +import javax.xml.transform.TransformerException; + +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.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +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.boot.test.mock.mockito.MockBean; +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 com.google.common.collect.Lists; + +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.RegisterResult; +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.exception.ManualFixNecessaryException; +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.service.RegisterSearchService.RegisterOperationStatus; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService.RegisterStatusResults; +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.asitplus.eidas.specific.modules.auth.eidas.v2.utils.MatchingTaskUtils; +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.exception.Pvp2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnResponseValidationException; +import net.shibboleth.utilities.java.support.xml.ParserPool; + +@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"; +  private static final String BPK_FROM_ID_AUSTRIA = "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY="; + +  @Autowired +  protected MsConnectorDummyConfigMap authConfig; +  @Autowired +  private IdAustriaClientAuthMetadataProvider metadataProvider; +  @Autowired +  private IdAustriaClientAuthCredentialProvider credentialProvider; +  @Autowired +  private PvpMetadataResolverFactory metadataFactory; +  @Autowired +  private ReceiveMobilePhoneSignatureResponseTask task; +  @MockBean +  private RegisterSearchService registerSearchService; + +  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 { +    MockitoAnnotations.initMocks(this); +    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 { +    setupMetadataResolver(); +    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)); +    setupMetadataResolver(); +    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 { +    setupMetadataResolver(); +    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 { +    setupMetadataResolver(); +    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 { +    setupMetadataResolver(); +    initResponse("/data/Response_without_sig_with_error_userstop.xml", true); + +    task.execute(pendingReq, executionContext); + +    assertEquals("Transition To S16", true, executionContext.get(Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK)); + +  } + +  @Test +  public void httpPostValidSignedWithErrorAndNoSubCode() throws Exception { +    setupMetadataResolver(); +    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 { +    setupMetadataResolver(); +    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 { +    setupMetadataResolver(); +    initResponse("/data/Response_with_EID.xml", true); +    AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); +    SimpleEidasData eidData = createEidasDataMatchingToSamlResponse() +        .familyName("notmatching") +        .build(); +    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()); +  } + +  //TODO: implement new test that this test makes no sense any more +  @Ignore +  @Test +  public void httpPostValidSignedAssertionEidValid_NoRegisterResult() throws Exception { +    setupMetadataResolver(); +    initResponse("/data/Response_with_EID.xml", true); +    AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); +    SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); +    authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); +    RegisterStatusResults registerSearchResult = new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), +        Collections.emptyList(), Collections.emptyList()); +    MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); +     +    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()); +    assertNull("Matching BPK", session.getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK)); +    assertEquals("Transition To S16", true, executionContext.get(Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK)); +  } + +  @Test +  public void httpPostValidSignedAssertionEidValid_ExactlyOneRegisterResult() throws Exception { +    setupMetadataResolver(); +    initResponse("/data/Response_with_EID.xml", true); +    AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); +    SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); +    authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); +    RegisterStatusResults registerSearchResult = buildResultWithOneMatch(); +    MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); + +    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()); +    assertNull("Matching BPK", session.getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK)); +    assertNull("Transition To S16", executionContext.get(Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK)); +     +    //TODO: update this check because this task selects one result from MDS search result before and creates a new element +    //Mockito.verify(registerSearchService).step7aKittProcess(eq(registerSearchResult), eq(eidData)); +  } + +  //TODO: implement new test that this test makes no sense any more +  @Ignore +  @Test +  public void httpPostValidSignedAssertionEidValid_MoreThanOneRegisterResult() throws Exception { +    setupMetadataResolver(); +    initResponse("/data/Response_with_EID.xml", true); +    AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); +    SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); +    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(ManualFixNecessaryException.class, e.getOriginalException().getCause()); +    assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); +     +     +    AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class);     +    assertNull("Matching BPK", session.getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK)); +    assertNull("Transition To S16", executionContext.get(Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK)); +  } + +  @NotNull +  private RegisterStatusResults buildResultWithOneMatch() { +    return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), +        Collections.singletonList(RegisterResult.builder() +            .bpk(BPK_FROM_ID_AUSTRIA) +            .pseudonym(Arrays.asList("bar")) +            .givenName("foo") +            .familyName("foo") +            .dateOfBirth("bar") +            .build()),  +        Collections.emptyList()); +     +  } + +  @NotNull +  private RegisterStatusResults buildResultWithTwoMatches() { +    List<RegisterResult> results = Lists.newArrayList( +        RegisterResult.builder() +            .bpk(BPK_FROM_ID_AUSTRIA) +            .pseudonym(Arrays.asList("bar")) +            .givenName("foo") +            .familyName("foo") +            .dateOfBirth("bar") +            .build(), +        RegisterResult.builder() +            .bpk("bpk") +            .pseudonym(Arrays.asList("pseudonym")) +            .givenName("givenName") +            .familyName("familyName") +            .dateOfBirth("dateOfBirth") +            .build()); +     +    return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()),  +        results, Collections.emptyList()); +  } + +  private BigInteger generateRandomProcessId() { +    return new BigInteger(RandomStringUtils.randomNumeric(10)); +     +  } +   +  private SimpleEidasData.SimpleEidasDataBuilder createEidasDataMatchingToSamlResponse() { +    // data from "/data/Response_with_EID.xml" +    return SimpleEidasData.builder() +        .familyName("Mustermann") +        .givenName("Max") +        .dateOfBirth("1940-01-01"); +  } + +  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); +  } + +  private void setupMetadataResolver() throws Pvp2MetadataException { +    metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( +        METADATA_PATH, null, "jUnit IDP", null)); +  } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveOtherLoginMethodGuiResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveOtherLoginMethodGuiResponseTaskTest.java new file mode 100644 index 00000000..c6b2e1fe --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveOtherLoginMethodGuiResponseTaskTest.java @@ -0,0 +1,140 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SelectedLoginMethod; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveOtherLoginMethodGuiResponseTask; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +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.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.ActiveProfiles; +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 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" +}) +@ActiveProfiles(profiles = {"deprecatedConfig"}) +@WebAppConfiguration +public class ReceiveOtherLoginMethodGuiResponseTaskTest { + +  @Autowired +  private ReceiveOtherLoginMethodGuiResponseTask task; + +  private final ExecutionContextImpl executionContext = new ExecutionContextImpl(); +  private TestRequestImpl pendingReq; +  private MockHttpServletRequest httpReq; +  private MockHttpServletResponse httpResp; + +  /** +   * jUnit class initializer. +   */ +  @BeforeClass +  public static void classInitializer() { +    final String current = new java.io.File(".").toURI().toString(); +    System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_1.properties"); +  } + +  /** +   * jUnit test set-up. +   */ +  @Before +  public void initialize() { +    httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); +    httpResp = new MockHttpServletResponse(); +    RequestContextHolder.resetRequestAttributes(); +    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + +    pendingReq = new TestRequestImpl(); +    pendingReq.setAuthUrl("https://localhost/ms_connector"); +    pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); + +    LocaleContextHolder.resetLocaleContext(); +  } + +  @Test +  public void withMobileSignatureSelection() throws TaskExecutionException { +    testTransition(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN, Constants.TRANSITION_TO_GENERATE_MOBILE_PHONE_SIGNATURE_REQUEST_TASK); +  } + +  @Test +  public void withEidasSelection() throws TaskExecutionException { +    testTransition(SelectedLoginMethod.EIDAS_LOGIN, Constants.TRANSITION_TO_GENERATE_EIDAS_LOGIN); +  } + +  @Test +  public void withNoOtherLoginSelection() throws TaskExecutionException { +    testTransition(SelectedLoginMethod.NO_OTHER_LOGIN, Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK); +  } + +  public void testTransition(SelectedLoginMethod loginMethod, String expectedTransition) throws TaskExecutionException { +    httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, loginMethod.name()); + +    task.execute(pendingReq, executionContext); + +    assertFalse("wrong pendingReq auth flag", pendingReq.isAuthenticated()); +    assertFalse("wrong process-cancelled flag", executionContext.isProcessCancelled()); +    assertNotNull("no login-selection found", executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); +    assertEquals("Wrong login-selection found", loginMethod, executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); +    assertEquals("Next task", true, executionContext.get(expectedTransition)); +  } + +  public void withInvalidSelection() { +    httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, RandomStringUtils.randomAlphabetic(2)); + +    TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); +  } + +  @Test +  public void withNullSelection() { +    httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, "null"); + +    TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); +  } + +  @Test +  public void withEmptySelection() { +    httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, ""); + +    TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); +  } + +  @Test +  public void withoutLoginMethodSelection() { + +    TaskExecutionException e = assertThrows(TaskExecutionException.class, +        () -> task.execute(pendingReq, executionContext)); + +    assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); +    isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); +  } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/utils/JoseUtilsTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/utils/JoseUtilsTest.java index ad38e371..4da03622 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/utils/JoseUtilsTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/utils/JoseUtilsTest.java @@ -17,13 +17,11 @@ import org.jose4j.lang.JoseException;  import org.junit.Assert;  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.test.annotation.DirtiesContext;  import org.springframework.test.context.ContextConfiguration;  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask;  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.exceptions.EaafException; @@ -34,15 +32,14 @@ import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType;  import at.gv.egiz.eaaf.core.impl.data.Pair;  @RunWith(SpringJUnit4ClassRunner.class) -@PrepareForTest(CreateIdentityLinkTask.class)  @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml",      "/SpringTest-context_basic_mapConfig.xml"})  public class JoseUtilsTest { -   +    @Autowired private EaafKeyStoreFactory keyStoreFactory; -   +    private static final List<String> AUTH_ALGORITHM_WHITELIST_SIGNING = Collections.unmodifiableList(        Arrays.asList(            AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256, @@ -50,48 +47,48 @@ public class JoseUtilsTest {            AlgorithmIdentifiers.RSA_PSS_USING_SHA256,            AlgorithmIdentifiers.RSA_PSS_USING_SHA512)); -   +    @Test    public void missingKey() throws EaafException, JoseException, KeyStoreException, IOException { -     +      KeyStoreConfiguration config = new KeyStoreConfiguration();      config.setFriendlyName("jUnittest");      config.setKeyStoreType(KeyStoreType.JKS);      config.setSoftKeyStoreFilePath("../data/junit.jks");      config.setSoftKeyStorePassword("password"); -     +      Pair<KeyStore, Provider> keyStore = keyStoreFactory.buildNewKeyStore(config);      String payLoad = RandomStringUtils.randomAlphanumeric(100); -     +      //check signing      try {        JoseUtils.createSignature(keyStore, "notExist", "password".toCharArray(), payLoad , true, "jUnitTest");        Assert.fail("missing Key not detected"); -       -    } catch (EaafException e) {       + +    } catch (EaafException e) {        Assert.assertEquals("ErrorId", "internal.keystore.09", e.getErrorId()); -       +      }    } -   +    @Test    public void createRsaSignature() throws EaafException, JoseException, KeyStoreException, IOException { -     +      KeyStoreConfiguration config = new KeyStoreConfiguration();      config.setFriendlyName("jUnittest");      config.setKeyStoreType(KeyStoreType.JKS);      config.setSoftKeyStoreFilePath("../data/junit.jks");      config.setSoftKeyStorePassword("password"); -     +      Pair<KeyStore, Provider> keyStore = keyStoreFactory.buildNewKeyStore(config);      String payLoad = RandomStringUtils.randomAlphanumeric(100); -     +      //check signing      String result = JoseUtils.createSignature(keyStore, "meta", "password".toCharArray(), payLoad , true, "jUnitTest"); -    +      Assert.assertNotNull("signed message", result);      Assert.assertFalse("signed msg empty", result.isEmpty()); -     +      //validate      List<X509Certificate> trustedCerts = EaafKeyStoreUtils.readCertsFromKeyStore(keyStore.getFirst()); @@ -99,30 +96,30 @@ public class JoseUtilsTest {          AUTH_ALGORITHM_WHITELIST_SIGNING              .toArray(new String[AUTH_ALGORITHM_WHITELIST_SIGNING.size()]));      JwsResult verify = JoseUtils.validateSignature(result, trustedCerts, constraints); -     +      Assert.assertTrue("sig. verify", verify.isValid());      Assert.assertEquals("payload", payLoad, verify.getPayLoad()); -         +    } -   +    @Test    public void createEccSignature() throws EaafException, JoseException, KeyStoreException, IOException { -     +      KeyStoreConfiguration config = new KeyStoreConfiguration();      config.setFriendlyName("jUnittest");      config.setKeyStoreType(KeyStoreType.JKS);      config.setSoftKeyStoreFilePath("../data/junit.jks");      config.setSoftKeyStorePassword("password"); -     +      Pair<KeyStore, Provider> keyStore = keyStoreFactory.buildNewKeyStore(config);      String payLoad = RandomStringUtils.randomAlphanumeric(100); -     +      //check signing      String result = JoseUtils.createSignature(keyStore, "sig", "password".toCharArray(), payLoad , true, "jUnitTest"); -    +      Assert.assertNotNull("signed message", result);      Assert.assertFalse("signed msg empty", result.isEmpty()); -     +      //validate      List<X509Certificate> trustedCerts = EaafKeyStoreUtils.readCertsFromKeyStore(keyStore.getFirst()); @@ -130,10 +127,10 @@ public class JoseUtilsTest {          AUTH_ALGORITHM_WHITELIST_SIGNING              .toArray(new String[AUTH_ALGORITHM_WHITELIST_SIGNING.size()]));      JwsResult verify = JoseUtils.validateSignature(result, trustedCerts, constraints); -     +      Assert.assertTrue("sig. verify", verify.isValid());      Assert.assertEquals("payload", payLoad, verify.getPayLoad()); -         +    } -   +  } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasAttributePostProcessingTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasAttributePostProcessingTest.java index 9bb51cd9..0a4ab851 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasAttributePostProcessingTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasAttributePostProcessingTest.java @@ -30,7 +30,7 @@ import java.text.SimpleDateFormat;  import java.util.HashMap;  import java.util.Map; -import org.joda.time.DateTime; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData;  import org.junit.BeforeClass;  import org.junit.Test;  import org.junit.runner.RunWith; @@ -41,7 +41,6 @@ import org.springframework.test.context.ContextConfiguration;  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  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.service.CcSpecificEidProcessingService;  @RunWith(SpringJUnit4ClassRunner.class) @@ -59,7 +58,7 @@ public class EidasAttributePostProcessingTest {        "DE/AT/532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25";    private static final String P1_GIVENNAME = "Max";    private static final String P1_FAMILYNAME = "Mustermann"; -  private static final DateTime P1_DATEOFBIRTH = DateTime.now(); +  private static final String P1_DATEOFBIRTH = "2020-01-04";    private static final String P1_PLACEOFBIRTH = "Nirgendwo";    private static final String P1_BIRTHNAME = "Musterkind"; @@ -68,7 +67,7 @@ public class EidasAttributePostProcessingTest {        "DE/AT/532eaabd9574880dbf76b9b8cc00832c20A6ec113d682299550d7a6e0f345e25";    private static final String P3_GIVENNAME = "Max";    private static final String P3_FAMILYNAME = "Mustermann"; -  private static final DateTime P3_DATEOFBIRTH = DateTime.now(); +  private static final String P3_DATEOFBIRTH = "2020-01-03";    private static final String P3_PLACEOFBIRTH = "Nirgendwo";    private static final String P3_BIRTHNAME = "Musterkind"; @@ -77,7 +76,7 @@ public class EidasAttributePostProcessingTest {        "DE/AT/532EAABD9574880DBF76B9B8CC00832C20A6EC113D682299550D7A6E0F345E25";    private static final String P4_GIVENNAME = "Max";    private static final String P4_FAMILYNAME = "Mustermann"; -  private static final DateTime P4_DATEOFBIRTH = DateTime.now(); +  private static final String P4_DATEOFBIRTH = "2020-01-05";    private static final String P4_PLACEOFBIRTH = "Nirgendwo";    private static final String P4_BIRTHNAME = "Musterkind"; @@ -86,7 +85,7 @@ public class EidasAttributePostProcessingTest {        "DE/AT/532EAABD9574880DBF76B9B8CC00832C20A6EC113D682299550D7A6E0F345E251";    private static final String P5_GIVENNAME = "Max";    private static final String P5_FAMILYNAME = "Mustermann"; -  private static final DateTime P5_DATEOFBIRTH = DateTime.now(); +  private static final String P5_DATEOFBIRTH = "2020-01-06";    private static final String P5_PLACEOFBIRTH = "Nirgendwo";    private static final String P5_BIRTHNAME = "Musterkind"; @@ -94,7 +93,7 @@ public class EidasAttributePostProcessingTest {    private static final String P6_eIDASID = "DE/AT/532EAABD9574880DBF76B9B8CC00832C20A6EC113D682299550D7A6E0F";    private static final String P6_GIVENNAME = "Max";    private static final String P6_FAMILYNAME = "Mustermann"; -  private static final DateTime P6_DATEOFBIRTH = DateTime.now(); +  private static final String P6_DATEOFBIRTH = "2020-01-08";    private static final String P6_PLACEOFBIRTH = "Nirgendwo";    private static final String P6_BIRTHNAME = "Musterkind"; @@ -102,7 +101,7 @@ public class EidasAttributePostProcessingTest {    private static final String P7_eIDASID = "DE/AT/532EAABD9574880DBF76B9B8CC00832C20A6EC113D682299550D7A6E0F";    private static final String P7_GIVENNAME = "Max";    private static final String P7_FAMILYNAME = "Mustermann"; -  private static final DateTime P7_DATEOFBIRTH = DateTime.now(); +  private static final String P7_DATEOFBIRTH = "2020-01-09";    private static final String P7_PLACEOFBIRTH = "Nirgendwo";    private static final String P7_BIRTHNAME = "Musterkind"; @@ -110,13 +109,13 @@ public class EidasAttributePostProcessingTest {        "EE/AT/asfasfasdfasdfasdfasdfasdfasvafasdfasdfasdfasdfasdfasvascasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasd";    private static final String P2_GIVENNAME = "Max";    private static final String P2_FAMILYNAME = "Mustermann"; -  private static final DateTime P2_DATEOFBIRTH = DateTime.now(); +  private static final String P2_DATEOFBIRTH = "2020-01-10";    private static final String P2_PLACEOFBIRTH = "Nirgendwo";    private static final String P2_BIRTHNAME = "Musterkind";    /**     * jUnit class initializer. -   *  +   *     * @throws IOException In case of an error     */    @BeforeClass @@ -129,7 +128,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void deWithHexLowerCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                P1_eIDASID,                P1_FAMILYNAME, @@ -156,7 +155,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void deWithHexMixedCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                P3_eIDASID,                P3_FAMILYNAME, @@ -183,7 +182,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void deWithHexUpperCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                P4_eIDASID,                P4_FAMILYNAME, @@ -270,7 +269,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void eeTestCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                P2_eIDASID,                P2_FAMILYNAME, @@ -297,7 +296,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void eeTestFamilyNameMissingCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                P2_eIDASID,                null, @@ -326,7 +325,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void eeTestGivenNameMissingCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                P2_eIDASID,                P2_FAMILYNAME, @@ -355,7 +354,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void eeTestDateOfBirthMissingCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                P2_eIDASID,                P2_FAMILYNAME, @@ -384,7 +383,7 @@ public class EidasAttributePostProcessingTest {    @Test    public void eeTestIdMissingCase() throws Exception {      try { -      final ErnbEidData result = postProcessor.postProcess( +      final SimpleEidasData result = postProcessor.postProcess(            generateInputData(                null,                P2_FAMILYNAME, @@ -411,7 +410,7 @@ public class EidasAttributePostProcessingTest {    }    private Map<String, Object> generateInputData(String id, String familyName, String givenName, -      DateTime dateOfBirth, String placeOfBirth, String birthName) { +                                                String dateOfBirth, String placeOfBirth, String birthName) {      final Map<String, Object> result = new HashMap<>();      result.put(Constants.eIDAS_ATTR_PERSONALIDENTIFIER, id);      result.put(Constants.eIDAS_ATTR_CURRENTGIVENNAME, givenName); @@ -423,8 +422,8 @@ public class EidasAttributePostProcessingTest {    } -  private void validate(ErnbEidData result, String id, String familyName, String givenName, -      DateTime dateOfBirth, String placeOfBirth, String birthName) { +  private void validate(SimpleEidasData result, String id, String familyName, String givenName, +                        String dateOfBirth, String placeOfBirth, String birthName) {      if (!result.getPseudonym().equals(id)) {        fail(result.getPseudonym() + "is not equal to " + id);      } @@ -441,12 +440,6 @@ public class EidasAttributePostProcessingTest {        fail(result.getDateOfBirth() + "is not equal to " + dateOfBirth);      } -    if (!result.getFormatedDateOfBirth().equals(new SimpleDateFormat("yyyy-MM-dd").format(dateOfBirth -        .toDate()))) { -      fail(result.getDateOfBirth() + "is not equal to " + new SimpleDateFormat("yyyy-MM-dd").format( -          dateOfBirth.toDate())); -    } -      if (!result.getPlaceOfBirth().equals(placeOfBirth)) {        fail(result.getPlaceOfBirth() + "is not equal to " + placeOfBirth);      } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingFirstTest.java index 7ac41500..84da2344 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingFirstTest.java @@ -54,8 +54,11 @@ import eu.eidas.auth.commons.light.impl.LightRequest.Builder;  @RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml", -    "/SpringTest-context_basic_realConfig.xml"}) -@TestPropertySource(locations = {"classpath:/config/junit_config_de_attributes.properties"}) +    "/SpringTest-context_basic_realConfig.xml", +    //"/SpringTest-context_basic_mapConfig.xml" +    }) +@TestPropertySource(locations = {"classpath:/config/junit_config_de_attributes.properties", "classpath:/config" + +    "/junit_config_1_springboot.properties"})  @DirtiesContext(classMode = ClassMode.AFTER_CLASS)  public class EidasRequestPreProcessingFirstTest { diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingSecondTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingSecondTest.java index 4a03fac1..6fd4f8a5 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingSecondTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasRequestPreProcessingSecondTest.java @@ -103,7 +103,7 @@ public class EidasRequestPreProcessingSecondTest {      final LightRequest lightReq = authnRequestBuilder.build(); -    Assert.assertEquals("ProviderName is not Static", "myNode", lightReq.getProviderName()); +    Assert.assertEquals("ProviderName is not Static", "myNode", lightReq.getProviderName());//Fixme "myNode"      Assert.assertEquals("no PublicSP", "public", lightReq.getSpType());      Assert.assertEquals("Requested attribute size not match", 8, lightReq.getRequestedAttributes().size()); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasResponseValidatorTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasResponseValidatorTest.java index e0f15c8c..0b18815b 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasResponseValidatorTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/validation/EidasResponseValidatorTest.java @@ -12,7 +12,6 @@ import org.junit.Assert;  import org.junit.Before;  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.test.annotation.DirtiesContext;  import org.springframework.test.context.ContextConfiguration; @@ -25,7 +24,6 @@ import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummySp  import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants;  import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasValidationException;  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.validator.EidasResponseValidator;  import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants;  import at.gv.egiz.eaaf.core.api.data.EaafConstants; @@ -41,7 +39,6 @@ import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse;  import lombok.val;  @RunWith(SpringJUnit4ClassRunner.class) -@PrepareForTest(CreateIdentityLinkTask.class)  @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)  @ContextConfiguration(locations = {      "/SpringTest-context_tasks_test.xml", @@ -50,17 +47,17 @@ public class EidasResponseValidatorTest {    @Autowired private MsConnectorDummyConfigMap basicConfig;    @Autowired protected EidasAttributeRegistry attrRegistry; -   +    private TestRequestImpl pendingReq;    private MsConnectorDummySpConfiguration oaParam; -   -   + +    /**     * jUnit test set-up.     */    @Before    public void setUp() throws EaafStorageException, URISyntaxException { -     +      final Map<String, String> spConfig = new HashMap<>();      spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp");      spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); @@ -74,250 +71,250 @@ public class EidasResponseValidatorTest {      pendingReq.setAuthUrl("http://test.com/");      pendingReq.setTransactionId("avaasbav");      pendingReq.setPiiTransactionId(RandomStringUtils.randomAlphanumeric(10)); -         +    } -   -   + +    @Test    public void loaFromResponseToLow() throws URISyntaxException {      //set-up -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        "LU/AT/" + RandomStringUtils.randomNumeric(10),  +    ILightResponse eidasResponse = buildDummyAuthResponse( +        "LU/AT/" + RandomStringUtils.randomNumeric(10),          EaafConstants.EIDAS_LOA_LOW,          false);      String spCountry = "AT";      String citizenCountryCode = "XX"; -                     +      //execute test      try {        EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, citizenCountryCode, attrRegistry);        Assert.fail("Wrong eIDAS response not detected"); -       +      } catch (EidasValidationException e) { -      Assert.assertEquals("ErrorId", "eidas.06", e.getErrorId());     +      Assert.assertEquals("ErrorId", "eidas.06", e.getErrorId());        Assert.assertEquals("wrong parameter size", 1, e.getParams().length); -      Assert.assertEquals("wrong errorMsg", "http://eidas.europa.eu/LoA/low",  +      Assert.assertEquals("wrong errorMsg", "http://eidas.europa.eu/LoA/low",            e.getParams()[0]); -   -    }     + +    }    } -   +    @Test    public void noEidasSpCountry() throws URISyntaxException {      //set-up -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        "LU/AT/" + RandomStringUtils.randomNumeric(10),  +    ILightResponse eidasResponse = buildDummyAuthResponse( +        "LU/AT/" + RandomStringUtils.randomNumeric(10),          EaafConstants.EIDAS_LOA_SUBSTANTIAL,          false);      String spCountry = null;      String citizenCountryCode = "LU"; -     +      oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH, EaafConstants.EIDAS_LOA_SUBSTANTIAL)); -     -                     + +      //execute test      try {        EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, citizenCountryCode, attrRegistry);        Assert.fail("Wrong eIDAS response not detected"); -       +      } catch (EidasValidationException e) { -      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());     +      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());        Assert.assertEquals("wrong parameter size", 2, e.getParams().length); -      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",  +      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",            e.getParams()[0]); -      Assert.assertEquals("wrong errorMsg",  -          "Destination country does not match to SP country",  +      Assert.assertEquals("wrong errorMsg", +          "Destination country does not match to SP country",            e.getParams()[1]); -   -    }     + +    }    } -   +    @Test    public void noEidasResponseCountry() throws URISyntaxException {      //set-up -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        "LU/AT/" + RandomStringUtils.randomNumeric(10),  +    ILightResponse eidasResponse = buildDummyAuthResponse( +        "LU/AT/" + RandomStringUtils.randomNumeric(10),          EaafConstants.EIDAS_LOA_SUBSTANTIAL,          false);      String spCountry = "AT";      String citizenCountryCode = null; -     +      oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH, EaafConstants.EIDAS_LOA_SUBSTANTIAL)); -     -                     + +      //execute test      try {        EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, citizenCountryCode, attrRegistry);        Assert.fail("Wrong eIDAS response not detected"); -       +      } catch (EidasValidationException e) { -      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());     +      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());        Assert.assertEquals("wrong parameter size", 2, e.getParams().length); -      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",  +      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",            e.getParams()[0]); -      Assert.assertEquals("wrong errorMsg",  -          "Citizen country does not match to eIDAS-node country that generates the response",  +      Assert.assertEquals("wrong errorMsg", +          "Citizen country does not match to eIDAS-node country that generates the response",            e.getParams()[1]); -   -    }     + +    }    } -   +    @Test    public void wrongEidasResponseCountry() throws URISyntaxException {      //set-up -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        "LU/AT/" + RandomStringUtils.randomNumeric(10),  +    ILightResponse eidasResponse = buildDummyAuthResponse( +        "LU/AT/" + RandomStringUtils.randomNumeric(10),          EaafConstants.EIDAS_LOA_SUBSTANTIAL,          false);      String spCountry = "AT";      String citizenCountryCode = "XX"; -     +      oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH, EaafConstants.EIDAS_LOA_SUBSTANTIAL)); -     -                     + +      //execute test      try {        EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, citizenCountryCode, attrRegistry);        Assert.fail("Wrong eIDAS response not detected"); -       +      } catch (EidasValidationException e) { -      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());     +      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());        Assert.assertEquals("wrong parameter size", 2, e.getParams().length); -      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",  +      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",            e.getParams()[0]); -      Assert.assertEquals("wrong errorMsg",  -          "Citizen country does not match to eIDAS-node country that generates the response",  +      Assert.assertEquals("wrong errorMsg", +          "Citizen country does not match to eIDAS-node country that generates the response",            e.getParams()[1]); -   -    }     + +    }    } -   +    @Test    public void missingPersonalIdentifier() throws URISyntaxException {      //set-up -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        null,  +    ILightResponse eidasResponse = buildDummyAuthResponse( +        null,          EaafConstants.EIDAS_LOA_SUBSTANTIAL,          false);      String spCountry = "AT";      String citizenCountryCode = "LU"; -     +      oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH, EaafConstants.EIDAS_LOA_SUBSTANTIAL)); -     -                     + +      //execute test      try {        EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, citizenCountryCode, attrRegistry);        Assert.fail("Wrong eIDAS response not detected"); -       +      } catch (EidasValidationException e) { -      Assert.assertEquals("ErrorId", "eidas.05", e.getErrorId());     +      Assert.assertEquals("ErrorId", "eidas.05", e.getErrorId());        Assert.assertEquals("wrong parameter size", 1, e.getParams().length); -      Assert.assertEquals("wrong errorMsg", "NO 'PersonalIdentifier' attriubte",  +      Assert.assertEquals("wrong errorMsg", "NO 'PersonalIdentifier' attriubte",            e.getParams()[0]); -   -    }     + +    }    } -   +    @Test    public void moreThanOnePersonalIdentifier() throws URISyntaxException {      //set-up -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        null,  +    ILightResponse eidasResponse = buildDummyAuthResponse( +        null,          EaafConstants.EIDAS_LOA_SUBSTANTIAL,          true);      String spCountry = "AT";      String citizenCountryCode = "LU"; -     +      oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH, EaafConstants.EIDAS_LOA_SUBSTANTIAL)); -     -                     + +      //execute test      try {        EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, citizenCountryCode, attrRegistry);        Assert.fail("Wrong eIDAS response not detected"); -       +      } catch (EidasValidationException e) { -      Assert.assertEquals("ErrorId", "eidas.05", e.getErrorId());     +      Assert.assertEquals("ErrorId", "eidas.05", e.getErrorId());        Assert.assertEquals("wrong parameter size", 1, e.getParams().length); -      Assert.assertEquals("wrong errorMsg", "NO 'PersonalIdentifier' attriubte",  +      Assert.assertEquals("wrong errorMsg", "NO 'PersonalIdentifier' attriubte",            e.getParams()[0]); -   -    }     + +    }    } -   +    @Test    public void emptyPersonalIdentifier() throws URISyntaxException {      //set-up -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        "",  +    ILightResponse eidasResponse = buildDummyAuthResponse( +        "",          EaafConstants.EIDAS_LOA_SUBSTANTIAL,          false);      String spCountry = "AT";      String citizenCountryCode = "LU"; -     +      oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH, EaafConstants.EIDAS_LOA_SUBSTANTIAL)); -     -                     + +      //execute test      try {        EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, citizenCountryCode, attrRegistry);        Assert.fail("Wrong eIDAS response not detected"); -       +      } catch (EidasValidationException e) { -      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());     +      Assert.assertEquals("ErrorId", "eidas.07", e.getErrorId());        Assert.assertEquals("wrong parameter size", 2, e.getParams().length); -      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",  +      Assert.assertEquals("wrong errorMsg", "PersonIdentifier",            e.getParams()[0]); -      Assert.assertEquals("wrong errorMsg",  -          "Wrong identifier format",  +      Assert.assertEquals("wrong errorMsg", +          "Wrong identifier format",            e.getParams()[1]); -   -    }     + +    }    } -   +    @Test    public void validResponse() throws URISyntaxException, EidasValidationException {      //set-up -     +      String spCountry = RandomStringUtils.randomAlphabetic(2).toUpperCase();      String cCountry = RandomStringUtils.randomAlphabetic(2).toUpperCase(); -     -    ILightResponse eidasResponse = buildDummyAuthResponse(  -        cCountry + "/" + spCountry + "/" + RandomStringUtils.randomAlphanumeric(20),  + +    ILightResponse eidasResponse = buildDummyAuthResponse( +        cCountry + "/" + spCountry + "/" + RandomStringUtils.randomAlphanumeric(20),          EaafConstants.EIDAS_LOA_SUBSTANTIAL,          false); -     +      oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH, EaafConstants.EIDAS_LOA_SUBSTANTIAL)); -     -                     + +      //execute test      EidasResponseValidator.validateResponse(pendingReq, eidasResponse, spCountry, cCountry, attrRegistry); -     +    } -   -   -  private AuthenticationResponse buildDummyAuthResponse(String personalId, String loa, boolean moreThanOnePersonalId)  + + +  private AuthenticationResponse buildDummyAuthResponse(String personalId, String loa, boolean moreThanOnePersonalId)        throws URISyntaxException { -     -         + +      final AttributeDefinition personIdattributeDef = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(          Constants.eIDAS_ATTR_PERSONALIDENTIFIER).first();      final Builder attributeMap = ImmutableAttributeMap.builder();      if (personalId != null) {        if (moreThanOnePersonalId) { -        ImmutableSet values = ImmutableSet.of(new StringAttributeValue(personalId),  +        ImmutableSet values = ImmutableSet.of(new StringAttributeValue(personalId),              new StringAttributeValue("XX/YY/" + RandomStringUtils.randomAlphanumeric(10))); -        attributeMap.put(personIdattributeDef, values);  -         +        attributeMap.put(personIdattributeDef, values); +        } else {          attributeMap.put(personIdattributeDef, personalId); -         -      }       + +      }      } -     +      val b = new AuthenticationResponse.Builder();      return b.id("_".concat(Random.nextHexRandom16()))          .issuer(RandomStringUtils.randomAlphabetic(10)) diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_lazy.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_lazy.xml new file mode 100644 index 00000000..a567ecba --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_lazy.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" +  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +  xmlns:context="http://www.springframework.org/schema/context" +  xmlns:tx="http://www.springframework.org/schema/tx" +  xmlns:aop="http://www.springframework.org/schema/aop" +  xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd +    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd +    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd +    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" > + +  <context:annotation-config /> + +  <import resource="classpath:/spring/eaaf_utils.beans.xml"/> + +  <bean id="idAustriaAuthCredentialProvider" +        class="at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider"  +        lazy-init="true" /> + +  <bean id="dummyPvpConfig" +        class="at.gv.egiz.eaaf.modules.pvp2.idp.test.dummy.DummyPvpConfiguration" +        lazy-init="true" /> + +</beans> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml index cd2888c1..f4fc72a7 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml @@ -12,6 +12,9 @@    <context:annotation-config /> + +  <bean id="eidasConnectorMessageSource" +        class="at.asitplus.eidas.specific.modules.auth.eidas.v2.config.EidasConnectorMessageSource"/>    <bean id="SZRClientForeIDAS"      class="at.asitplus.eidas.specific.modules.auth.eidas.v2.szr.SzrClient" /> 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 60ecfa8c..f4463a3e 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 @@ -18,6 +18,8 @@    <import resource="SpringTest-context_authManager.xml" />    <import resource="SpringTest-context_basic_test.xml" />   +  <import resource="classpath:/eidas_v2_auth.beans.xml"/> +  <import resource="classpath:/eaaf_pvp.beans.xml" />    <bean id="mvcGUIBuilderImpl"      class="at.asitplus.eidas.specific.connector.gui.SpringMvcGuiFormBuilderImpl" /> @@ -25,6 +27,15 @@    <bean id="springManagedSpecificConnectorCommunicationService"      class="at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummySpecificCommunicationService" /> +  <bean id="dummyPvpConfig" +        class="at.gv.egiz.eaaf.modules.pvp2.idp.test.dummy.DummyPvpConfiguration" /> + +  <bean id="dummyGuiConfigFactory" +        class="at.gv.egiz.eaaf.core.impl.idp.module.gui.DummyGuiBuilderConfigurationFactory" /> +   +  <bean id="dummyVelocityBuilder" +        class="at.gv.egiz.eaaf.core.impl.idp.module.gui.DummyVelocityGuiFormBuilder" /> +    <bean id="specificConnectorAttributesFileWithPath"      class="java.lang.String">      <constructor-arg @@ -37,31 +48,5 @@        value="src/test/resources/config/additional-attributes.xml" />    </bean> -  <bean id="attributeRegistry" -    class="at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry"> -    <property name="eidasAttributesFile" -      ref="specificConnectorAttributesFileWithPath" /> -    <property name="additionalAttributesFile" -      ref="specificConnectorAdditionalAttributesFileWithPath" /> -  </bean> - -  <bean id="authBlockSigningService" -        class="at.asitplus.eidas.specific.modules.auth.eidas.v2.service.AuthBlockSigningService" /> - -  <bean id="EidasSignalServlet" -        class="at.asitplus.eidas.specific.modules.auth.eidas.v2.EidasSignalServlet" /> - -  <!-- Authentication Process Tasks --> -  <bean id="ConnecteIDASNodeTask" -    class="at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateAuthnRequestTask" -    scope="prototype" /> - -  <bean id="ReceiveResponseFromeIDASNodeTask" -    class="at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAuthnResponseTask" -    scope="prototype" /> - -  <bean id="CreateIdentityLinkTask" -    class="at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.CreateIdentityLinkTask" -    scope="prototype" />  </beans>
\ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_1.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_1.properties index a662379c..9e6876f4 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_1.properties +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_1.properties @@ -8,15 +8,20 @@ eidas.ms.context.use.clustermode=true  eidas.ms.monitoring.eIDASNode.metadata.url= +eidas.ms.client.http.connection.timeout.socket=1 +eidas.ms.client.http.connection.timeout.connection=1 +eidas.ms.client.http.connection.timeout.request=1 + +  ##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.static.directory=../../../../../../basicConfig/webcontent/ +eidas.ms.webcontent.templates=../../../../../../basicConfig/templates/ +eidas.ms.webcontent.properties=../../../../../../basicConfig/properties/messages  ## extended validation of pending-request Id's  eidas.ms.core.pendingrequestid.maxlifetime=300 @@ -88,6 +93,13 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.4=LegalPerson,tr  eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true +#### matching###### +# ZMR communication +eidas.ms.auth.eIDAS.zmrclient.endpoint=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.zmrclient.req.organisation.behoerdennr=jUnit123456 +eidas.ms.auth.eIDAS.zmrclient.req.update.reason.code=EIDAS-KITT + +  ## PVP2 S-Profile end-point configuration  eidas.ms.pvp2.keystore.path=keys/.....  eidas.ms.pvp2.keystore.password= @@ -114,4 +126,28 @@ 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 +eidas.ms.configuration.pvp.enable.entitycategories= + + + + +## PVP2 S-Profile ID Austria client configuration + +eidas.ms.modules.idaustriaclient.keystore.path=../keystore/junit_test.jks +eidas.ms.modules.idaustriaclient.keystore.password=password +eidas.ms.modules.idaustriaclient.keystore.type=jks + +eidas.ms.modules.idaustriaclient.metadata.sign.alias=meta +eidas.ms.modules.idaustriaclient.metadata.sign.password=password +eidas.ms.modules.idaustriaclient.request.sign.alias=sig +eidas.ms.modules.idaustriaclient.request.sign.password=password +eidas.ms.modules.idaustriaclient.response.encryption.alias=enc +eidas.ms.modules.idaustriaclient.response.encryption.password=password + +eidas.ms.modules.idaustriaclient.truststore.path=../keystore/junit_test.jks +eidas.ms.modules.idaustriaclient.truststore.password=password +eidas.ms.modules.idaustriaclient.truststore.type=jks + +eidas.ms.modules.idaustriaclient.idaustria.idp.entityId= +eidas.ms.modules.idaustriaclient.idaustria.idp.metadataUrl= + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_1_springboot.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_1_springboot.properties new file mode 100644 index 00000000..224e1b1f --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_1_springboot.properties @@ -0,0 +1,132 @@ +## embbeded Tomcat +tomcat.workingdir=./target/work +tomcat.ajp.enabled=true +tomcat.ajp.port=8009 +tomcat.ajp.networkAddress=127.0.0.1 +tomcat.ajp.additionalAttributes.secretrequired=true +tomcat.ajp.additionalAttributes.secret=junit + +## Basic service configuration +eidas.ms.context.url.prefix=http://localhost +eidas.ms.core.configRootDir=file:./src/test/resources/config/ + +eidas.ms.context.use.clustermode=true + +##Monitoring +eidas.ms.monitoring.eIDASNode.metadata.url=http://localhost:40900/mockup + +## extended validation of pending-request Id's +eidas.ms.core.pendingrequestid.digist.secret=pendingReqIdSecret + +## eIDAS Ref. Implementation connector ### +eidas.ms.auth.eIDAS.node_v2.forward.endpoint=http://eidas.node/junit + +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=jks +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= + +#tech. AuthBlock signing for E-ID process +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=keys/teststore.jks +eidas.ms.auth.eIDAS.authblock.keystore.type=jks +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.debug.logfullmessages=true +eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution=false + + +#### matching###### +# ZMR communication +eidas.ms.auth.eIDAS.zmrclient.endpoint=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.zmrclient.ssl.keyStore.type=jks +eidas.ms.auth.eIDAS.zmrclient.ssl.keyStore.path=keys/junit.jks +eidas.ms.auth.eIDAS.zmrclient.ssl.keyStore.password=password +eidas.ms.auth.eIDAS.zmrclient.ssl.trustStore.path= +eidas.ms.auth.eIDAS.zmrclient.ssl.trustStore.password= + +eidas.ms.auth.eIDAS.zmrclient.req.organisation.behoerdennr=jUnit123456 +eidas.ms.auth.eIDAS.zmrclient.req.update.reason.code=EIDAS-KITT +eidas.ms.auth.eIDAS.zmrclient.req.update.reason.text=KITT for eIDAS Matching + + +## 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=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 +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=https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/metadata +eidas.ms.sp.0.pvp2.metadata.truststore=keys/junit.jks +eidas.ms.sp.0.pvp2.metadata.truststore.password=password +eidas.ms.sp.0.friendlyName=jUnit test +eidas.ms.sp.0.newEidMode=true + +#eidas.ms.sp.0.pvp2.metadata.url= +#eidas.ms.sp.0.policy.allowed.requested.targets=.* +#eidas.ms.sp.0.policy.hasBaseIdTransferRestriction=false + +## Service Provider configuration +eidas.ms.sp.1.uniqueID=https://demo.egiz.gv.at/junit_test +eidas.ms.sp.1.pvp2.metadata.truststore=keys/junit.jks +eidas.ms.sp.1.pvp2.metadata.truststore.password=password +eidas.ms.sp.1.friendlyName=jUnit test +eidas.ms.sp.1.pvp2.metadata.url=http://junit.test/metadata +eidas.ms.sp.1.policy.allowed.requested.targets=test +eidas.ms.sp.1.policy.hasBaseIdTransferRestriction=true + +## PVP2 S-Profile client configuration +#eidas.ms.modules.idaustriaclient.keystore.type=jks +#eidas.ms.modules.idaustriaclient.keystore.path=keys/junit.jks1 +#eidas.ms.modules.idaustriaclient.keystore.password=password +#eidas.ms.modules.idaustriaclient.key.metadata.alias=meta +#eidas.ms.modules.idaustriaclient.key.metadata.password=password +#eidas.ms.modules.idaustriaclient.key.signing.alias=sig +#eidas.ms.modules.idaustriaclient.key.signing.password=password +#eidas.ms.modules.idaustriaclient.metadata.validity=24 + +eidas.ms.modules.idaustriaclient.keystore.path=keys/junit_test.jks +eidas.ms.modules.idaustriaclient.keystore.password=password +eidas.ms.modules.idaustriaclient.keystore.type=jks + +eidas.ms.modules.idaustriaclient.metadata.sign.alias=meta +eidas.ms.modules.idaustriaclient.metadata.sign.password=password +eidas.ms.modules.idaustriaclient.request.sign.alias=sig +eidas.ms.modules.idaustriaclient.request.sign.password=password +eidas.ms.modules.idaustriaclient.response.encryption.alias=enc +eidas.ms.modules.idaustriaclient.response.encryption.password=password + +eidas.ms.modules.idaustriaclient.truststore.path=keys/junit_test.jks +eidas.ms.modules.idaustriaclient.truststore.password=password +eidas.ms.modules.idaustriaclient.truststore.type=jks + +eidas.ms.modules.idaustriaclient.idaustria.idp.entityId= +eidas.ms.modules.idaustriaclient.idaustria.idp.metadataUrl= + +eidas.ms.modules.idaustriaclient.metadata.organisation.name=JUnit +eidas.ms.modules.idaustriaclient.metadata.organisation.friendyname=For testing with jUnit +eidas.ms.modules.idaustriaclient.metadata.organisation.url=http://junit.test +eidas.ms.modules.idaustriaclient.metadata.contact.givenname=Max +eidas.ms.modules.idaustriaclient.metadata.contact.surname=Mustermann +eidas.ms.modules.idaustriaclient.metadata.contact.email=max@junit.test + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_2.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_2.properties index 7c5e5a40..f07f86f6 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_2.properties +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_2.properties @@ -86,6 +86,13 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.4=LegalPerson,tr  eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true +#### matching###### +# ZMR communication +eidas.ms.auth.eIDAS.zmrclient.endpoint=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.zmrclient.req.organisation.behoerdennr=jUnit123456 +eidas.ms.auth.eIDAS.zmrclient.req.update.reason.code=EIDAS-KITT + +  ## PVP2 S-Profile end-point configuration  eidas.ms.pvp2.keystore.path=keys/.....  eidas.ms.pvp2.keystore.password= 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 c830d447..7b975752 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 @@ -88,6 +88,13 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.4=LegalPerson,tr  eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true +#### matching###### +# ZMR communication +eidas.ms.auth.eIDAS.zmrclient.endpoint=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.zmrclient.req.organisation.behoerdennr=jUnit123456 +eidas.ms.auth.eIDAS.zmrclient.req.update.reason.code=EIDAS-KITT + +  ## PVP2 S-Profile end-point configuration  eidas.ms.pvp2.keystore.path=keys/.....  eidas.ms.pvp2.keystore.password= diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_4.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_4.properties index 01e72069..7fda2871 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_4.properties +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_4.properties @@ -86,6 +86,13 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.4=LegalPerson,tr  eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true +#### matching###### +# ZMR communication +eidas.ms.auth.eIDAS.zmrclient.endpoint=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.zmrclient.req.organisation.behoerdennr=jUnit123456 +eidas.ms.auth.eIDAS.zmrclient.req.update.reason.code=EIDAS-KITT + +  ## PVP2 S-Profile end-point configuration  eidas.ms.pvp2.keystore.path=keys/.....  eidas.ms.pvp2.keystore.password= diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_de_attributes.properties b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_de_attributes.properties index 6b235667..0cdb4459 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_de_attributes.properties +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/junit_config_de_attributes.properties @@ -88,6 +88,13 @@ eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.4=LegalPerson,tr  eidas.ms.auth.eIDAS.node_v2.attributes.requested.representation.5=LegalName,true +#### matching###### +# ZMR communication +eidas.ms.auth.eIDAS.zmrclient.endpoint=http://localhost:1234/demoszr +eidas.ms.auth.eIDAS.zmrclient.req.organisation.behoerdennr=jUnit123456 +eidas.ms.auth.eIDAS.zmrclient.req.update.reason.code=EIDAS-KITT + +  ## PVP2 S-Profile end-point configuration  eidas.ms.pvp2.keystore.path=keys/.....  eidas.ms.pvp2.keystore.password= diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/keys/junit_test.jks b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/keys/junit_test.jksBinary files differ new file mode 100644 index 00000000..ee6254a9 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/keys/junit_test.jks diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/keys/teststore.jks b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/keys/teststore.jksBinary files differ new file mode 100644 index 00000000..fcc6400c --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/config/keys/teststore.jks diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_with_EID.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_with_EID.xml new file mode 100644 index 00000000..10701c29 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_with_EID.xml @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8"?> +<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://localhost/authhandler/sp/idaustria/post" InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> +	<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">classpath:/data/idp_metadata_classpath_entity.xml</saml2:Issuer> +	<saml2p:Status> +		<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/> +	</saml2p:Status> +	<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_602c3236bffaf71ac3ac88674e76ff9f" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0"> +		<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp/metadata</saml2:Issuer> +		<saml2:Subject> +			<saml2:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" NameQualifier="urn:publicid:gv.at:cdid+BF">QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:NameID> +			<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> +				<saml2:SubjectConfirmationData InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" NotOnOrAfter="2014-03-05T06:44:51.017Z" Recipient="https://localhost/authhandler/sp/idaustria/post"/> +			</saml2:SubjectConfirmation> +		</saml2:Subject> +		<saml2:Conditions NotBefore="2014-03-05T06:39:51.017Z" NotOnOrAfter="2014-03-05T06:44:51.017Z"> +			<saml2:AudienceRestriction> +				<saml2:Audience>https://localhost/authhandler/sp/idaustria/metadata</saml2:Audience> +			</saml2:AudienceRestriction> +		</saml2:Conditions> +		<saml2:AuthnStatement AuthnInstant="2014-03-05T06:39:51.017Z" SessionIndex="_c0c683509a8ff6ac372a9cf9c5c5a406"> +			<saml2:AuthnContext> +				<saml2:AuthnContextClassRef>http://eidas.europa.eu/LoA/high</saml2:AuthnContextClassRef> +			</saml2:AuthnContext> +		</saml2:AuthnStatement> +		<saml2:AttributeStatement> +			<saml2:Attribute FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Mustermann</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2.1</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">http://eidas.europa.eu/LoA/low</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">IT</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Max</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1940-01-01</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:AttributeValue> +			</saml2:Attribute> +            <saml2:Attribute FriendlyName="userAuthBlock" Name="urn:eidgvat:attributes.authblock.signed" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +              <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQGEwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMwMDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SYO4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eTOWdiQX0GpDIBspYMZh8ZKcwwCgYIKoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImnAiA2KwFtzO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA==</saml2:AttributeValue> +            </saml2:Attribute> +		</saml2:AttributeStatement> +	</saml2:Assertion> +</saml2p:Response> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_with_wrong_destination_endpoint.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_with_wrong_destination_endpoint.xml new file mode 100644 index 00000000..c21381d9 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_with_wrong_destination_endpoint.xml @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="UTF-8"?> +<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" +				 Destination="https://localhost/authhandler/idAustriaSp1/post" +				 InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> +	<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">classpath:/data/idp_metadata_classpath_entity.xml</saml2:Issuer> +	<saml2p:Status> +		<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/> +	</saml2p:Status> +	<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_602c3236bffaf71ac3ac88674e76ff9f" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0"> +		<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp/metadata</saml2:Issuer> +		<saml2:Subject> +			<saml2:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" NameQualifier="urn:publicid:gv.at:cdid+BF">QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:NameID> +			<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> +				<saml2:SubjectConfirmationData InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" +											   NotOnOrAfter="2014-03-05T06:44:51.017Z" +											   Recipient="https://localhost/authhandler/idAustriaSp1/post"/> +			</saml2:SubjectConfirmation> +		</saml2:Subject> +		<saml2:Conditions NotBefore="2014-03-05T06:39:51.017Z" NotOnOrAfter="2014-03-05T06:44:51.017Z"> +			<saml2:AudienceRestriction> +				<saml2:Audience>https://demo.egiz.gv.at/demoportal_demologin/</saml2:Audience> +			</saml2:AudienceRestriction> +		</saml2:Conditions> +		<saml2:AuthnStatement AuthnInstant="2014-03-05T06:39:51.017Z" SessionIndex="_c0c683509a8ff6ac372a9cf9c5c5a406"> +			<saml2:AuthnContext> +				<saml2:AuthnContextClassRef>http://www.stork.gov.eu/1.0/citizenQAALevel/4</saml2:AuthnContextClassRef> +			</saml2:AuthnContext> +		</saml2:AuthnStatement> +		<saml2:AttributeStatement> +			<saml2:Attribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2.1</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Mustermann</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Max</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1940-01-01</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-CITIZEN-QAA-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.94" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:integer">4</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">AT</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-SECTOR-FOR-IDENTIFIER" Name="urn:oid:1.2.40.0.10.2.1.1.261.34" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">urn:publicid:gv.at:cdid+BF</saml2:AttributeValue> +			</saml2:Attribute> +		</saml2:AttributeStatement> +	</saml2:Assertion> +</saml2p:Response> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_classpath_entityid.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_classpath_entityid.xml new file mode 100644 index 00000000..1c3bd357 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_classpath_entityid.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://localhost/authhandler/sp/idaustria/post" InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> +	<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">classpath:/data/idp_metadata_classpath_entity.xml</saml2:Issuer> +	<saml2p:Status> +		<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/> +	</saml2p:Status> +	<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_602c3236bffaf71ac3ac88674e76ff9f" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0"> +		<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp/metadata</saml2:Issuer> +		<saml2:Subject> +			<saml2:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" NameQualifier="urn:publicid:gv.at:cdid+BF">QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:NameID> +			<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> +				<saml2:SubjectConfirmationData InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" NotOnOrAfter="2014-03-05T06:44:51.017Z" Recipient="https://localhost/authhandler/sp/idaustria/post"/> +			</saml2:SubjectConfirmation> +		</saml2:Subject> +		<saml2:Conditions NotBefore="2014-03-05T06:39:51.017Z" NotOnOrAfter="2014-03-05T06:44:51.017Z"> +			<saml2:AudienceRestriction> +				<saml2:Audience>https://localhost/authhandler/sp/idaustria/metadata</saml2:Audience> +			</saml2:AudienceRestriction> +		</saml2:Conditions> +		<saml2:AuthnStatement AuthnInstant="2014-03-05T06:39:51.017Z" SessionIndex="_c0c683509a8ff6ac372a9cf9c5c5a406"> +			<saml2:AuthnContext> +				<saml2:AuthnContextClassRef>http://eidas.europa.eu/LoA/high</saml2:AuthnContextClassRef> +			</saml2:AuthnContext> +		</saml2:AuthnStatement> +		<saml2:AttributeStatement> +			<saml2:Attribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2.1</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Mustermann</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Max</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1940-01-01</saml2:AttributeValue> +			</saml2:Attribute> + +			<saml2:Attribute FriendlyName="EID-CITIZEN-QAA- EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">http://eidas.europa.eu/LoA/high</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">IT</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-SECTOR-FOR-IDENTIFIER" Name="urn:oid:1.2.40.0.10.2.1.1.261.34" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">urn:publicid:gv.at:cdid+BF</saml2:AttributeValue> +			</saml2:Attribute> +		</saml2:AttributeStatement> +	</saml2:Assertion> +</saml2p:Response> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error.xml new file mode 100644 index 00000000..2d7020ac --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://localhost/authhandler/sp/idaustria/post" InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> +	<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">classpath:/data/idp_metadata_classpath_entity.xml</saml2:Issuer> +	<saml2p:Status> +		<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder"> +          <saml2p:StatusCode Value="9199"/> +        </saml2p:StatusCode> +        <saml2p:StatusMessage>Der Anmeldevorgang wurde durch den Benutzer abgebrochen.</saml2p:StatusMessage> +	</saml2p:Status> +	<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_602c3236bffaf71ac3ac88674e76ff9f" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0"> +		<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp/metadata</saml2:Issuer> +		<saml2:Subject> +			<saml2:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" NameQualifier="urn:publicid:gv.at:cdid+BF">QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:NameID> +			<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> +				<saml2:SubjectConfirmationData InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" NotOnOrAfter="2014-03-05T06:44:51.017Z" Recipient="https://localhost/authhandler/sp/idaustria/post"/> +			</saml2:SubjectConfirmation> +		</saml2:Subject> +		<saml2:Conditions NotBefore="2014-03-05T06:39:51.017Z" NotOnOrAfter="2014-03-05T06:44:51.017Z"> +			<saml2:AudienceRestriction> +				<saml2:Audience>https://localhost/authhandler/sp/idaustria/metadata</saml2:Audience> +			</saml2:AudienceRestriction> +		</saml2:Conditions> +		<saml2:AuthnStatement AuthnInstant="2014-03-05T06:39:51.017Z" SessionIndex="_c0c683509a8ff6ac372a9cf9c5c5a406"> +			<saml2:AuthnContext> +				<saml2:AuthnContextClassRef>http://eidas.europa.eu/LoA/high</saml2:AuthnContextClassRef> +			</saml2:AuthnContext> +		</saml2:AuthnStatement> +		<saml2:AttributeStatement> +			<saml2:Attribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2.1</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">http://eidas.europa.eu/LoA/low</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">IT</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="eidBind" Name="urn:eidgvat:attributes.eidbind" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">aabbccddeeffgghh</saml2:AttributeValue> +			</saml2:Attribute> +            <saml2:Attribute FriendlyName="userConsent" Name="urn:eidgvat:attributes.consent.signed" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +              <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQGEwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMwMDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SYO4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eTOWdiQX0GpDIBspYMZh8ZKcwwCgYIKoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImnAiA2KwFtzO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA==</saml2:AttributeValue> +            </saml2:Attribute> +		</saml2:AttributeStatement> +	</saml2:Assertion> +</saml2p:Response> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_empty_subcode.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_empty_subcode.xml new file mode 100644 index 00000000..36fd9c11 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_empty_subcode.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://localhost/authhandler/sp/idaustria/post" InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> +	<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">classpath:/data/idp_metadata_classpath_entity.xml</saml2:Issuer> +	<saml2p:Status> +		<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder"> +          <saml2p:StatusCode Value=""/> +        </saml2p:StatusCode> +        <saml2p:StatusMessage>Der Anmeldevorgang wurde durch den Benutzer abgebrochen.</saml2p:StatusMessage> +	</saml2p:Status> +	<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_602c3236bffaf71ac3ac88674e76ff9f" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0"> +		<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp/metadata</saml2:Issuer> +		<saml2:Subject> +			<saml2:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" NameQualifier="urn:publicid:gv.at:cdid+BF">QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:NameID> +			<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> +				<saml2:SubjectConfirmationData InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" NotOnOrAfter="2014-03-05T06:44:51.017Z" Recipient="https://localhost/authhandler/sp/idaustria/post"/> +			</saml2:SubjectConfirmation> +		</saml2:Subject> +		<saml2:Conditions NotBefore="2014-03-05T06:39:51.017Z" NotOnOrAfter="2014-03-05T06:44:51.017Z"> +			<saml2:AudienceRestriction> +				<saml2:Audience>https://localhost/authhandler/sp/idaustria/metadata</saml2:Audience> +			</saml2:AudienceRestriction> +		</saml2:Conditions> +		<saml2:AuthnStatement AuthnInstant="2014-03-05T06:39:51.017Z" SessionIndex="_c0c683509a8ff6ac372a9cf9c5c5a406"> +			<saml2:AuthnContext> +				<saml2:AuthnContextClassRef>http://eidas.europa.eu/LoA/high</saml2:AuthnContextClassRef> +			</saml2:AuthnContext> +		</saml2:AuthnStatement> +		<saml2:AttributeStatement> +			<saml2:Attribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2.1</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">http://eidas.europa.eu/LoA/low</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">IT</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="eidBind" Name="urn:eidgvat:attributes.eidbind" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">aabbccddeeffgghh</saml2:AttributeValue> +			</saml2:Attribute> +            <saml2:Attribute FriendlyName="userConsent" Name="urn:eidgvat:attributes.consent.signed" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +              <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQGEwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMwMDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SYO4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eTOWdiQX0GpDIBspYMZh8ZKcwwCgYIKoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImnAiA2KwFtzO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA==</saml2:AttributeValue> +            </saml2:Attribute> +		</saml2:AttributeStatement> +	</saml2:Assertion> +</saml2p:Response> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_userstop.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_userstop.xml new file mode 100644 index 00000000..989d3053 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_userstop.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://localhost/authhandler/sp/idaustria/post" InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> +	<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">classpath:/data/idp_metadata_classpath_entity.xml</saml2:Issuer> +	<saml2p:Status> +		<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder"> +          <saml2p:StatusCode Value="1005"/> +        </saml2p:StatusCode> +        <saml2p:StatusMessage>Der Anmeldevorgang wurde durch den Benutzer abgebrochen.</saml2p:StatusMessage> +	</saml2p:Status> +	<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_602c3236bffaf71ac3ac88674e76ff9f" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0"> +		<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp/metadata</saml2:Issuer> +		<saml2:Subject> +			<saml2:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" NameQualifier="urn:publicid:gv.at:cdid+BF">QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:NameID> +			<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> +				<saml2:SubjectConfirmationData InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" NotOnOrAfter="2014-03-05T06:44:51.017Z" Recipient="https://localhost/authhandler/sp/idaustria/post"/> +			</saml2:SubjectConfirmation> +		</saml2:Subject> +		<saml2:Conditions NotBefore="2014-03-05T06:39:51.017Z" NotOnOrAfter="2014-03-05T06:44:51.017Z"> +			<saml2:AudienceRestriction> +				<saml2:Audience>https://localhost/authhandler/sp/idaustria/metadata</saml2:Audience> +			</saml2:AudienceRestriction> +		</saml2:Conditions> +		<saml2:AuthnStatement AuthnInstant="2014-03-05T06:39:51.017Z" SessionIndex="_c0c683509a8ff6ac372a9cf9c5c5a406"> +			<saml2:AuthnContext> +				<saml2:AuthnContextClassRef>http://eidas.europa.eu/LoA/high</saml2:AuthnContextClassRef> +			</saml2:AuthnContext> +		</saml2:AuthnStatement> +		<saml2:AttributeStatement> +			<saml2:Attribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2.1</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">http://eidas.europa.eu/LoA/low</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">IT</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="eidBind" Name="urn:eidgvat:attributes.eidbind" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">aabbccddeeffgghh</saml2:AttributeValue> +			</saml2:Attribute> +            <saml2:Attribute FriendlyName="userConsent" Name="urn:eidgvat:attributes.consent.signed" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +              <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQGEwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMwMDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SYO4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eTOWdiQX0GpDIBspYMZh8ZKcwwCgYIKoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImnAiA2KwFtzO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA==</saml2:AttributeValue> +            </saml2:Attribute> +		</saml2:AttributeStatement> +	</saml2:Assertion> +</saml2p:Response> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_without_subcode.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_without_subcode.xml new file mode 100644 index 00000000..c85cb655 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/Response_without_sig_with_error_without_subcode.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://localhost/authhandler/sp/idaustria/post" InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> +	<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">classpath:/data/idp_metadata_classpath_entity.xml</saml2:Issuer> +	<saml2p:Status> +		<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder"> +        </saml2p:StatusCode> +        <saml2p:StatusMessage>Der Anmeldevorgang wurde durch den Benutzer abgebrochen.</saml2p:StatusMessage> +	</saml2p:Status> +	<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_602c3236bffaf71ac3ac88674e76ff9f" IssueInstant="2014-03-05T06:39:51.017Z" Version="2.0"> +		<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://demo.egiz.gv.at/demoportal_moaid-2.0/pvp/metadata</saml2:Issuer> +		<saml2:Subject> +			<saml2:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" NameQualifier="urn:publicid:gv.at:cdid+BF">QVGm48cqcM4UcyhDTNGYmVdrIoY=</saml2:NameID> +			<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> +				<saml2:SubjectConfirmationData InResponseTo="_aeebfae3ce681fe3ddcaf213a42f01d3" NotOnOrAfter="2014-03-05T06:44:51.017Z" Recipient="https://localhost/authhandler/sp/idaustria/post"/> +			</saml2:SubjectConfirmation> +		</saml2:Subject> +		<saml2:Conditions NotBefore="2014-03-05T06:39:51.017Z" NotOnOrAfter="2014-03-05T06:44:51.017Z"> +			<saml2:AudienceRestriction> +				<saml2:Audience>https://localhost/authhandler/sp/idaustria/metadata</saml2:Audience> +			</saml2:AudienceRestriction> +		</saml2:Conditions> +		<saml2:AuthnStatement AuthnInstant="2014-03-05T06:39:51.017Z" SessionIndex="_c0c683509a8ff6ac372a9cf9c5c5a406"> +			<saml2:AuthnContext> +				<saml2:AuthnContextClassRef>http://eidas.europa.eu/LoA/high</saml2:AuthnContextClassRef> +			</saml2:AuthnContext> +		</saml2:AuthnStatement> +		<saml2:AttributeStatement> +			<saml2:Attribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2.1</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">http://eidas.europa.eu/LoA/low</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">IT</saml2:AttributeValue> +			</saml2:Attribute> +			<saml2:Attribute FriendlyName="eidBind" Name="urn:eidgvat:attributes.eidbind" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +				<saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">aabbccddeeffgghh</saml2:AttributeValue> +			</saml2:Attribute> +            <saml2:Attribute FriendlyName="userConsent" Name="urn:eidgvat:attributes.consent.signed" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"> +              <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQGEwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMwMDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SYO4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eTOWdiQX0GpDIBspYMZh8ZKcwwCgYIKoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImnAiA2KwFtzO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA==</saml2:AttributeValue> +            </saml2:Attribute> +		</saml2:AttributeStatement> +	</saml2:Assertion> +</saml2p:Response> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_classpath_entity.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_classpath_entity.xml new file mode 100644 index 00000000..080a189f --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_classpath_entity.xml @@ -0,0 +1,146 @@ +<?xml version="1.0" encoding="UTF-8"?> +<md:EntityDescriptor +        xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" +        ID="_1a48ec3432f2f3ba6222724a5b06f873" +        entityID="classpath:/data/idp_metadata_classpath_entity.xml" +        validUntil="2045-02-06T08:47:26.211Z"> +    <md:IDPSSODescriptor +            WantAuthnRequestsSigned="true" +            protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> +        <md:KeyDescriptor use="signing"> +            <ds:KeyInfo +                    xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +                <ds:X509Data> +                    <ds:X509Certificate>MIIDMzCCAhsCBFtIcPowDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVH +                        SVoxJDAiBgNVBAsMG2NlbnRyYWwgbmF0aW9uYWwgZUlEQVMgbm9kZTEaMBgGA1UEAwwRQXNzZXJ0 +                        aW9uIHNpZ25pbmcwHhcNMTgwNzEzMDkyOTMwWhcNMjEwNDA3MDkyOTMwWjBeMQswCQYDVQQGEwJB +                        VDENMAsGA1UECgwERUdJWjEkMCIGA1UECwwbY2VudHJhbCBuYXRpb25hbCBlSURBUyBub2RlMRow +                        GAYDVQQDDBFBc3NlcnRpb24gc2lnbmluZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +                        AJ5zDYxMPRcz6AHaev1tS46Tq8sdgbGFM56uxk6c7LmMDC+HTzNX/3Q5S/YwSzgL3ue5TSw1ltOf +                        yMXMZ6D0+buWWcsxGEkQ8M3adKRFdQrEwafzwTA7pguq5WiHOkr4qwR7dLMome9z5cc3LRcwdOPP +                        gq7ahb5jM3hRqc5xkMWIuvql0NFXPzlHrjDLwy5nIWPOhL5abhVt4YsXbpbjXxFSGkDEAZ32K3EU +                        LNBr9FSUmJfbrVX9AU2T+BKIwiqXP8e/3UJHgPHQ0l5ljWp5P6u5+tvM21o8sUM4eArRa8BkdRsP +                        C92GVuASSUz2ZJ3JhAK1cSM8bnvaZVLQtTvPMAcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAAp7z +                        TubWXW6YMpyLSvWBdZiiQ3X66XpSZLZJDIAkoPzEY0DSBp8I5YASIx4JTR5XJt+6MI9acgNIAYW8 +                        DhtRwUMVaRWEtuCrfKhGLWm5KSxnhPcD3lzRZhY4ZcA7dUlirjf6hnqo2TFEmJ9fkM+rxwy1GkDD +                        7j2YDSOFmSq9/Ud9/IbIfSnRu/lO0dh7iRrmg3y0Y/+plPxYmp4AHqehP11OchTz2FGGHVsSC2Vs +                        IVBQI6ANZYyOlicgfEEFHA06jP9OnA0EwEFr2P+di9caZg8vfibyzxMGeuf6CY0c0eLHokBCn2W8 +                        vkzvWiER3pozRvCmXFjCVZfRjUunaJf2ow== +                    </ds:X509Certificate> +                </ds:X509Data> +                <ds:X509Data> +                    <ds:X509Certificate>MIIC+DCCAeCgAwIBAgIEXh7TbTANBgkqhkiG9w0BAQsFADA+MQswCQYDVQQGEwJB +                        VDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxEDAOBgNVBAMMB3NpZ25p +                        bmcwHhcNMjAwMTE1MDg1NTA5WhcNMjkwMTE0MDg1NTA5WjA+MQswCQYDVQQGEwJB +                        VDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxEDAOBgNVBAMMB3NpZ25p +                        bmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCUSiRjnDvPafZfhJ+L +                        1wM86FKJX3VIAV/8TD9qJ6HOBkn5WwYfpheyCfRb6XVDyIGpO8qnMWAgC17Ngbmh +                        zj8d8HXNQ2l3uppMv24oUTfXyYhQfZWAghx0sTlRIx/ZmlnduJilx2S53Sa7ruJw +                        lQcBFXj9h9B8dtyegc86Sx6D9BumP1xU7+mEBk8Gv9rR5Khg0Y7qGfZWB0t4aikg +                        aupWveVwiGifOOSfR8czqIg9qUpMYfZiTEBTSRmN6sPiNWhd4J0GyAI9Rn5C9jz/ +                        sSlQrxpN+4DXzsqSU5F6gzq3yRux6wyOzDlt2birf21VPQ9HIy4YCjZXwgDWG7AO +                        821pAgMBAAEwDQYJKoZIhvcNAQELBQADggEBADnwdaxUtQU6SIpYwIb2c0ljTmQi +                        7ryUcUpNHtK0M0E5Mw5Ex8zwrWbNQZ2sUyc4r07M66iOIqHsYZUQlRYvVKHifDpA +                        r8TCgD7iGGdB3By8Ou0RaNW+03w1fwmi98CufbHCGvpv0o2KxlejoHZminNdQ79i +                        bN+01nhocezJQATEQlnwHLiQSjilXpZeLYDk8HbrcUXNRxezN4ChdH+uU54vf+Ux +                        qcj9QHcmBe1+BM8EXfqS1DbTwZl+NTCnh5OYl8fvIFSOHMBxwFrI4pyY0faxg9Uc +                        rCogn/oQ+mV1gnVUDaDhvvEnVGZQtrlt7heVId2BeNellVgsrcmdW8j4U9U= +                    </ds:X509Certificate> +                </ds:X509Data> +                <ds:X509Data> +                    <ds:X509Certificate>MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQGEwJBVDEN +                        MAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRh +                        MB4XDTIwMDExNTA4NTQxNVoXDTMwMDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQx +                        DTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0 +                        YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SY +                        O4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eTOWdiQX0GpDIBspYMZh8ZKcwwCgYI +                        KoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImn +                        AiA2KwFtzO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA== +                    </ds:X509Certificate> +                </ds:X509Data> +            </ds:KeyInfo> +        </md:KeyDescriptor> +        <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent +        </md:NameIDFormat> +        <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient +        </md:NameIDFormat> +        <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified +        </md:NameIDFormat> +        <md:SingleSignOnService +                Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" +                Location="https://vidp.gv.at/ms_connector/pvp/post" /> +        <md:SingleSignOnService +                Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" +                Location="https://vidp.gv.at/ms_connector/pvp/redirect" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="PRINCIPAL-NAME" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.20" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-CCS-URL" Name="urn:oid:1.2.40.0.10.2.1.1.261.64" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-ISSUING-NATION" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.32" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-SOURCE-PIN" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.36" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-SIGNER-CERTIFICATE" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.66" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-SECTOR-FOR-IDENTIFIER" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.34" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-SOURCE-PIN-TYPE" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.104" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-E-ID-TOKEN" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.39" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-IDENTITY-LINK" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.38" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.108" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +        <saml2:Attribute +                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" +                FriendlyName="EID-IDENTITY-STATUS-LEVEL" +                Name="urn:oid:1.2.40.0.10.2.1.1.261.109" +                NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" /> +    </md:IDPSSODescriptor> +</md:EntityDescriptor> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_no_sig.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_no_sig.xml new file mode 100644 index 00000000..bc55fe62 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_no_sig.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="_1a48ec3432f2f3ba6222724a5b06f873" entityID="https://vidp.gv.at/ms_connector/pvp/metadata" validUntil="2045-02-06T08:47:26.211Z"> +	<md:IDPSSODescriptor WantAuthnRequestsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> +		<md:KeyDescriptor use="signing"> +			<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +				<ds:X509Data> +					<ds:X509Certificate>MIIDMzCCAhsCBFtIcPowDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVH +SVoxJDAiBgNVBAsMG2NlbnRyYWwgbmF0aW9uYWwgZUlEQVMgbm9kZTEaMBgGA1UEAwwRQXNzZXJ0 +aW9uIHNpZ25pbmcwHhcNMTgwNzEzMDkyOTMwWhcNMjEwNDA3MDkyOTMwWjBeMQswCQYDVQQGEwJB +VDENMAsGA1UECgwERUdJWjEkMCIGA1UECwwbY2VudHJhbCBuYXRpb25hbCBlSURBUyBub2RlMRow +GAYDVQQDDBFBc3NlcnRpb24gc2lnbmluZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AJ5zDYxMPRcz6AHaev1tS46Tq8sdgbGFM56uxk6c7LmMDC+HTzNX/3Q5S/YwSzgL3ue5TSw1ltOf +yMXMZ6D0+buWWcsxGEkQ8M3adKRFdQrEwafzwTA7pguq5WiHOkr4qwR7dLMome9z5cc3LRcwdOPP +gq7ahb5jM3hRqc5xkMWIuvql0NFXPzlHrjDLwy5nIWPOhL5abhVt4YsXbpbjXxFSGkDEAZ32K3EU +LNBr9FSUmJfbrVX9AU2T+BKIwiqXP8e/3UJHgPHQ0l5ljWp5P6u5+tvM21o8sUM4eArRa8BkdRsP +C92GVuASSUz2ZJ3JhAK1cSM8bnvaZVLQtTvPMAcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAAp7z +TubWXW6YMpyLSvWBdZiiQ3X66XpSZLZJDIAkoPzEY0DSBp8I5YASIx4JTR5XJt+6MI9acgNIAYW8 +DhtRwUMVaRWEtuCrfKhGLWm5KSxnhPcD3lzRZhY4ZcA7dUlirjf6hnqo2TFEmJ9fkM+rxwy1GkDD +7j2YDSOFmSq9/Ud9/IbIfSnRu/lO0dh7iRrmg3y0Y/+plPxYmp4AHqehP11OchTz2FGGHVsSC2Vs +IVBQI6ANZYyOlicgfEEFHA06jP9OnA0EwEFr2P+di9caZg8vfibyzxMGeuf6CY0c0eLHokBCn2W8 +vkzvWiER3pozRvCmXFjCVZfRjUunaJf2ow==</ds:X509Certificate> +				</ds:X509Data> +			</ds:KeyInfo> +		</md:KeyDescriptor> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat> +		<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://vidp.gv.at/ms_connector/pvp/post"/> +		<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://vidp.gv.at/ms_connector/pvp/redirect"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CCS-URL" Name="urn:oid:1.2.40.0.10.2.1.1.261.64" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN" Name="urn:oid:1.2.40.0.10.2.1.1.261.36" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SIGNER-CERTIFICATE" Name="urn:oid:1.2.40.0.10.2.1.1.261.66" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SECTOR-FOR-IDENTIFIER" Name="urn:oid:1.2.40.0.10.2.1.1.261.34" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN-TYPE" Name="urn:oid:1.2.40.0.10.2.1.1.261.104" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-E-ID-TOKEN" Name="urn:oid:1.2.40.0.10.2.1.1.261.39" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-LINK" Name="urn:oid:1.2.40.0.10.2.1.1.261.38" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-STATUS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.109" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +	</md:IDPSSODescriptor> +</md:EntityDescriptor> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_no_sig2.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_no_sig2.xml new file mode 100644 index 00000000..bdc176a0 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_no_sig2.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="_1a48ec3432f2f3ba6222724a5b06f873" entityID="classpath:/data/idp_metadata_no_sig2.xml" validUntil="2045-02-06T08:47:26.211Z"> +	<md:IDPSSODescriptor WantAuthnRequestsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> +		<md:KeyDescriptor use="signing"> +			<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +				<ds:X509Data> +					<ds:X509Certificate>MIIDMzCCAhsCBFtIcPowDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVH +SVoxJDAiBgNVBAsMG2NlbnRyYWwgbmF0aW9uYWwgZUlEQVMgbm9kZTEaMBgGA1UEAwwRQXNzZXJ0 +aW9uIHNpZ25pbmcwHhcNMTgwNzEzMDkyOTMwWhcNMjEwNDA3MDkyOTMwWjBeMQswCQYDVQQGEwJB +VDENMAsGA1UECgwERUdJWjEkMCIGA1UECwwbY2VudHJhbCBuYXRpb25hbCBlSURBUyBub2RlMRow +GAYDVQQDDBFBc3NlcnRpb24gc2lnbmluZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AJ5zDYxMPRcz6AHaev1tS46Tq8sdgbGFM56uxk6c7LmMDC+HTzNX/3Q5S/YwSzgL3ue5TSw1ltOf +yMXMZ6D0+buWWcsxGEkQ8M3adKRFdQrEwafzwTA7pguq5WiHOkr4qwR7dLMome9z5cc3LRcwdOPP +gq7ahb5jM3hRqc5xkMWIuvql0NFXPzlHrjDLwy5nIWPOhL5abhVt4YsXbpbjXxFSGkDEAZ32K3EU +LNBr9FSUmJfbrVX9AU2T+BKIwiqXP8e/3UJHgPHQ0l5ljWp5P6u5+tvM21o8sUM4eArRa8BkdRsP +C92GVuASSUz2ZJ3JhAK1cSM8bnvaZVLQtTvPMAcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAAp7z +TubWXW6YMpyLSvWBdZiiQ3X66XpSZLZJDIAkoPzEY0DSBp8I5YASIx4JTR5XJt+6MI9acgNIAYW8 +DhtRwUMVaRWEtuCrfKhGLWm5KSxnhPcD3lzRZhY4ZcA7dUlirjf6hnqo2TFEmJ9fkM+rxwy1GkDD +7j2YDSOFmSq9/Ud9/IbIfSnRu/lO0dh7iRrmg3y0Y/+plPxYmp4AHqehP11OchTz2FGGHVsSC2Vs +IVBQI6ANZYyOlicgfEEFHA06jP9OnA0EwEFr2P+di9caZg8vfibyzxMGeuf6CY0c0eLHokBCn2W8 +vkzvWiER3pozRvCmXFjCVZfRjUunaJf2ow==</ds:X509Certificate> +				</ds:X509Data> +			</ds:KeyInfo> +		</md:KeyDescriptor> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat> +		<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://vidp.gv.at/ms_connector/pvp/post"/> +		<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://vidp.gv.at/ms_connector/pvp/redirect"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CCS-URL" Name="urn:oid:1.2.40.0.10.2.1.1.261.64" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN" Name="urn:oid:1.2.40.0.10.2.1.1.261.36" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SIGNER-CERTIFICATE" Name="urn:oid:1.2.40.0.10.2.1.1.261.66" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SECTOR-FOR-IDENTIFIER" Name="urn:oid:1.2.40.0.10.2.1.1.261.34" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN-TYPE" Name="urn:oid:1.2.40.0.10.2.1.1.261.104" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-E-ID-TOKEN" Name="urn:oid:1.2.40.0.10.2.1.1.261.39" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-LINK" Name="urn:oid:1.2.40.0.10.2.1.1.261.38" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-STATUS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.109" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +	</md:IDPSSODescriptor> +</md:EntityDescriptor> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_sig_notvalid.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_sig_notvalid.xml new file mode 100644 index 00000000..86665a9c --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_sig_notvalid.xml @@ -0,0 +1,84 @@ +<?xml version="1.0" encoding="UTF-8"?> +<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="_1a48ec3432f2f3ba6222724a5b06f873" entityID="https://localEntity" validUntil="2045-02-06T08:47:26.211Z"> +  <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +    <ds:SignedInfo> +      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> +      <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> +      <ds:Reference URI="#_1a48ec3432f2f3ba6222724a5b06f873"> +        <ds:Transforms> +          <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> +          <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> +        </ds:Transforms> +        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> +        <ds:DigestValue>e6DiHa9scuvxJFBUipZ8PQcD4kAkmSIDZgZV+0/7glg=</ds:DigestValue> +      </ds:Reference> +    </ds:SignedInfo> +    <ds:SignatureValue>Czr2EwhK/0ZUZ5blQpJfNoOFEscLlxlmHPjmOJUIsxlB2pUn+ApULrjVpR1ViUcGZ0PVi2KChSNoSn09YKjtgPFBiSY010VYdaACgqluxUt6AwESObaqcyHVBzMDUr/g6jkRFEJV4vqnZQQDdDfTH4MXNqunORegS1saBHw4nJSOX4YfoVmIuT5uOlRrxvoG7srnGShvF7DmvIHBUBF5Tq9FyeSgwTM8udxl8Yl9FB2pREuR83CcbgjPrYKtzi6TiSfrWkcD0L5BvmMxN/BdaGDAorxYOnk41sWDJjrkY8C2SC1YDy6XT4SM06uFwstUrRn8QPg1hfbLHAyQNoaR8ecgapk5DkxmbATMcGY+SM4yQWkBdYT7GtufNmF8sIVaL6JOOTKAE9qqX/1N6N4zOPmm8rpIqVEQZtQ5usN/ubxbxLxUoTdDeo8RwkktW6zQ3Zv9+Iyf0DASYmK1IxN+fMw/qyeVy9r6o15ITHTqTmT/7BidKZ58m4HxIK52E3DU</ds:SignatureValue> +    <ds:KeyInfo> +      <ds:X509Data> +        <ds:X509Certificate>MIIEFTCCAn0CBFtIcMwwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVH +SVoxMTAvBgNVBAMMKG5hdGlvbmFsIGNlbnRyYWwgZUlEQVMgbm9kZSAtIHRlc3RzeXN0ZW0wHhcN +MTgwNzEzMDkyODQ0WhcNMjEwNDA3MDkyODQ0WjBPMQswCQYDVQQGEwJBVDENMAsGA1UECgwERUdJ +WjExMC8GA1UEAwwobmF0aW9uYWwgY2VudHJhbCBlSURBUyBub2RlIC0gdGVzdHN5c3RlbTCCAaIw +DQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALK4bdf5OremKkj0+xCjU0eN7RUd1A2VqoGnvFUs +t7xjLQ1PspHiDf9Pm2cwOIJabSnuZ01hYAGz9X+lU3Z3fwhVc+tEsuzsaAml/LPw3i3+ppoSTJDM +iDvhCoUKTzJ8HBQj2gTvXNlqPljyGneuCJ+uBMr7Okq/XjMTJj2xzvutrHS3qIO+/w+OkY967QLV +RXh0bdFqYqnyAnlYcWJPIwjanOJtE2difPYqers7ZW1F9djP0+IZRoyaook5rpLYvuQTHuvulgIE +3zGlTuOx3sk8zMyInMndqi75Eh+ROnndSZE7gN3u5CfFpuO5pxFa2jj1h/AnR39Tg8/sU+Se+AwH +rNvee3IWhxk5LkelYevfeCQos7Dv2ASE9XMCCs7FoE47w8fDalECh09MFKDiotpklbq3OrPg9NQ4 +D//k0GXlW5jYUKP/Wq/+suAI6mfhSnNkjOGMcMlzNTmwxGD/v7Py6OVA+YcJQsqYalLrqbvT2tXV +mYBVO3oqafg+kfevfwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBgQCioM8k0EEBFtY4QyxOYFufPDLw +9PNPct01ltnTVjNEEt/L6/8zYlDwrDeULEkJS7mV9zV3657NPQ5IPT/Ib93Uk/RPi0iOA2CGWIMa +DQIODN3BUYr+zPUqhbKS6OWOhTgV8GiRCUbxrT1uc1AiacP63pga3TJX8k8WFnfW+Dqm2MfWWlxr +4X2YB9VUW55X5sBNy035jYhEpp8NCK/fTAhoEQNCG+rm3T9qhT6YyOnbW2kXU747+ZwXT2qA5o4y +a/9+6dDc+LUlHCEm4X7c6bcGvCfNezB4k56FzbAJlOLf2VDGzvEQBf0hsB+kElezm1VBlEkZ4Mjz +pBpHBMoR21SwTpcvrbR4ig0Bk1eEHNK44sw0F32K5yww3gnJftMIZtPhjhk8UdG2/H6vs9s/to2V +j4V6wN4o79RTULoQ8RjL6MPWEWzwOvOZXJAo2XJEECvDivSjIJvNC0lfrK3zI3LH3c1JR6q2EfeC +Z50wTJMFoChSaqunJQXKo81g6wNhP00=</ds:X509Certificate> +      </ds:X509Data> +    </ds:KeyInfo> +  </ds:Signature> +  <md:IDPSSODescriptor WantAuthnRequestsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> +    <md:KeyDescriptor use="signing"> +      <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +        <ds:X509Data> +          <ds:X509Certificate>MIIDMzCCAhsCBFtIcPowDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVH +SVoxJDAiBgNVBAsMG2NlbnRyYWwgbmF0aW9uYWwgZUlEQVMgbm9kZTEaMBgGA1UEAwwRQXNzZXJ0 +aW9uIHNpZ25pbmcwHhcNMTgwNzEzMDkyOTMwWhcNMjEwNDA3MDkyOTMwWjBeMQswCQYDVQQGEwJB +VDENMAsGA1UECgwERUdJWjEkMCIGA1UECwwbY2VudHJhbCBuYXRpb25hbCBlSURBUyBub2RlMRow +GAYDVQQDDBFBc3NlcnRpb24gc2lnbmluZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AJ5zDYxMPRcz6AHaev1tS46Tq8sdgbGFM56uxk6c7LmMDC+HTzNX/3Q5S/YwSzgL3ue5TSw1ltOf +yMXMZ6D0+buWWcsxGEkQ8M3adKRFdQrEwafzwTA7pguq5WiHOkr4qwR7dLMome9z5cc3LRcwdOPP +gq7ahb5jM3hRqc5xkMWIuvql0NFXPzlHrjDLwy5nIWPOhL5abhVt4YsXbpbjXxFSGkDEAZ32K3EU +LNBr9FSUmJfbrVX9AU2T+BKIwiqXP8e/3UJHgPHQ0l5ljWp5P6u5+tvM21o8sUM4eArRa8BkdRsP +C92GVuASSUz2ZJ3JhAK1cSM8bnvaZVLQtTvPMAcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAAp7z +TubWXW6YMpyLSvWBdZiiQ3X66XpSZLZJDIAkoPzEY0DSBp8I5YASIx4JTR5XJt+6MI9acgNIAYW8 +DhtRwUMVaRWEtuCrfKhGLWm5KSxnhPcD3lzRZhY4ZcA7dUlirjf6hnqo2TFEmJ9fkM+rxwy1GkDD +7j2YDSOFmSq9/Ud9/IbIfSnRu/lO0dh7iRrmg3y0Y/+plPxYmp4AHqehP11OchTz2FGGHVsSC2Vs +IVBQI6ANZYyOlicgfEEFHA06jP9OnA0EwEFr2P+di9caZg8vfibyzxMGeuf6CY0c0eLHokBCn2W8 +vkzvWiER3pozRvCmXFjCVZfRjUunaJf2ow==</ds:X509Certificate> +        </ds:X509Data> +      </ds:KeyInfo> +    </md:KeyDescriptor> +    <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat> +    <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat> +    <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat> +    <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://vidp.gv.at/ms_connector/pvp/post"/> +    <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://vidp.gv.at/ms_connector/pvp/redirect"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CCS-URL" Name="urn:oid:1.2.40.0.10.2.1.1.261.64" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN" Name="urn:oid:1.2.40.0.10.2.1.1.261.36" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SIGNER-CERTIFICATE" Name="urn:oid:1.2.40.0.10.2.1.1.261.66" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SECTOR-FOR-IDENTIFIER" Name="urn:oid:1.2.40.0.10.2.1.1.261.34" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN-TYPE" Name="urn:oid:1.2.40.0.10.2.1.1.261.104" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-E-ID-TOKEN" Name="urn:oid:1.2.40.0.10.2.1.1.261.39" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-LINK" Name="urn:oid:1.2.40.0.10.2.1.1.261.38" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +    <saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-STATUS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.109" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +  </md:IDPSSODescriptor> +</md:EntityDescriptor> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_sig_valid_wrong_alg.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_sig_valid_wrong_alg.xml new file mode 100644 index 00000000..2187aa5f --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/idp_metadata_sig_valid_wrong_alg.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?><md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="_1a48ec3432f2f3ba6222724a5b06f873" entityID="https://vidp.gv.at/ms_connector/pvp/metadata" validUntil="2045-02-06T08:47:26.211Z"> +	<dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" Id="signature-1-1"><dsig:SignedInfo><dsig:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><dsig:Reference Id="reference-1-1" URI=""><dsig:Transforms><dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><dsig:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></dsig:Transforms><dsig:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><dsig:DigestValue>dhkHkgZ1OOHG0nYWiRXrpZhIAx41103CG6DKDbBra8o=</dsig:DigestValue></dsig:Reference></dsig:SignedInfo><dsig:SignatureValue>AkxnEu9g3QgYC0JwuJXMYFrnNn6UMtrbtVn5YzkKBXxyYqZui4pEi/TRSM9r7Gt+ +4UqHrJVkYMbbuoO2kpiDnluPG+vHYzYFvF0agQ+gfGjpVQNRORN0FU7JPX+KPjpr +sMU8wVZITSPU0GBBccvzrcpq7DQt0VbV5U7/Vq3KM/fop4ytAkUbTltUj/XxvAd1 +XdhB/zyeTTR2dafJ6Z2CKyM7MMmxwXYD1NrPGciPvTJ9ASHAT0lJM1dxrRNbeAja +KTrNVj78MhSluRm5g7N1pMZzgMSpqN66AUg8pkSTvcRaNImPzYDcMQzHl2Tr362M +RudjSgaEljK98TbBdgLFTg==</dsig:SignatureValue><dsig:KeyInfo><dsig:X509Data><dsig:X509Certificate>MIIEqzCCBBSgAwIBAgIHANux81oNezANBgkqhkiG9w0BAQUFADBAMSIwIAYDVQQD +ExlJQUlLIFRlc3QgSW50ZXJtZWRpYXRlIENBMQ0wCwYDVQQKEwRJQUlLMQswCQYD +VQQGEwJBVDAeFw0xMzA5MjcwNTMzMzdaFw0yMzA5MjcwNTMzMzdaMIHkMQswCQYD +VQQGEwJBVDENMAsGA1UEBxMER3JhejEmMCQGA1UEChMdR3JheiBVbml2ZXJzaXR5 +IG9mIFRlY2hub2xvZ3kxSDBGBgNVBAsTP0luc3RpdHV0ZSBmb3IgQXBwbGllZCBJ +bmZvcm1hdGlvbiBQcm9jZXNzaW5nIGFuZCBDb21tdW5pY2F0aW9uczEUMBIGA1UE +BBMLTU9BLVNTIFRlc3QxGDAWBgNVBCoTD0VHSVogVGVzdHBvcnRhbDEkMCIGA1UE +AxMbRUdJWiBUZXN0cG9ydGFsIE1PQS1TUyBUZXN0MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAuDjOyf+mY+oQL2FQzzuaiC8C23vVKbq/n2Zi7BqSibZH +mtqMJfmj4pT+hWSNHvVvWsaxFcx4KeNqdCMzwnw1r4P3Sf+2o5uFku5KHEMLMokR +yYQG9VqY/KkB94ye7Pv6zT8gvKqxGFg96UamECep4swPaSZrA8AOER5WAtyGDzKI +Tz+a5zfFaTXDoba7f98PCWR96yKiFjVOhzp38WVz4VJgz+b8ZSY7Xsv5Kn7DXjOL +STX4MevFLki3rFPup3+4vGToaMBW3PEj67HXBdqR855Le6+E6rVxORqsXqlVwhsI +6nuS0CO2LWYmBNR1IB0mXteeYH/HfxvuZc+7yDjdPQIDAQABo4IBhDCCAYAwDgYD +VR0PAQH/BAQDAgbAMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFEmcH6VY4BG1EAGB +TLoNR9vH/g6yMFAGA1UdHwRJMEcwRaBDoEGGP2h0dHA6Ly9jYS5pYWlrLnR1Z3Jh +ei5hdC9jYXBzby9jcmxzL0lBSUtUZXN0X0ludGVybWVkaWF0ZUNBLmNybDCBqgYI +KwYBBQUHAQEEgZ0wgZowSgYIKwYBBQUHMAGGPmh0dHA6Ly9jYS5pYWlrLnR1Z3Jh +ei5hdC9jYXBzby9PQ1NQP2NhPUlBSUtUZXN0X0ludGVybWVkaWF0ZUNBMEwGCCsG +AQUFBzAChkBodHRwOi8vY2EuaWFpay50dWdyYXouYXQvY2Fwc28vY2VydHMvSUFJ +S1Rlc3RfSW50ZXJtZWRpYXRlQ0EuY2VyMCEGA1UdEQQaMBiBFnRob21hcy5sZW56 +QGVnaXouZ3YuYXQwHwYDVR0jBBgwFoAUaKJeEdreL4BrRES/jfplNoEkp28wDQYJ +KoZIhvcNAQEFBQADgYEAlFGjUxXLs7SAT8NtXSrv2WrjlklaRnHTFHLQwyVo8JWb +gvRkHHDUv2o8ofXUY2R2WJ38dxeDoccgbXrJb/Qhi8IY7YhCwv/TuIZDisyAqo8W +ORKSip/6HWlGCSR/Vgoet1GtCmF0FoUxFUIGSAuQ2yyt4fIzt5GJrU1X5ujjI1w=</dsig:X509Certificate></dsig:X509Data></dsig:KeyInfo></dsig:Signature><md:IDPSSODescriptor WantAuthnRequestsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> +		<md:KeyDescriptor use="signing"> +			<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +				<ds:X509Data> +					<ds:X509Certificate>MIIDMzCCAhsCBFtIcPowDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVH +SVoxJDAiBgNVBAsMG2NlbnRyYWwgbmF0aW9uYWwgZUlEQVMgbm9kZTEaMBgGA1UEAwwRQXNzZXJ0 +aW9uIHNpZ25pbmcwHhcNMTgwNzEzMDkyOTMwWhcNMjEwNDA3MDkyOTMwWjBeMQswCQYDVQQGEwJB +VDENMAsGA1UECgwERUdJWjEkMCIGA1UECwwbY2VudHJhbCBuYXRpb25hbCBlSURBUyBub2RlMRow +GAYDVQQDDBFBc3NlcnRpb24gc2lnbmluZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AJ5zDYxMPRcz6AHaev1tS46Tq8sdgbGFM56uxk6c7LmMDC+HTzNX/3Q5S/YwSzgL3ue5TSw1ltOf +yMXMZ6D0+buWWcsxGEkQ8M3adKRFdQrEwafzwTA7pguq5WiHOkr4qwR7dLMome9z5cc3LRcwdOPP +gq7ahb5jM3hRqc5xkMWIuvql0NFXPzlHrjDLwy5nIWPOhL5abhVt4YsXbpbjXxFSGkDEAZ32K3EU +LNBr9FSUmJfbrVX9AU2T+BKIwiqXP8e/3UJHgPHQ0l5ljWp5P6u5+tvM21o8sUM4eArRa8BkdRsP +C92GVuASSUz2ZJ3JhAK1cSM8bnvaZVLQtTvPMAcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAAp7z +TubWXW6YMpyLSvWBdZiiQ3X66XpSZLZJDIAkoPzEY0DSBp8I5YASIx4JTR5XJt+6MI9acgNIAYW8 +DhtRwUMVaRWEtuCrfKhGLWm5KSxnhPcD3lzRZhY4ZcA7dUlirjf6hnqo2TFEmJ9fkM+rxwy1GkDD +7j2YDSOFmSq9/Ud9/IbIfSnRu/lO0dh7iRrmg3y0Y/+plPxYmp4AHqehP11OchTz2FGGHVsSC2Vs +IVBQI6ANZYyOlicgfEEFHA06jP9OnA0EwEFr2P+di9caZg8vfibyzxMGeuf6CY0c0eLHokBCn2W8 +vkzvWiER3pozRvCmXFjCVZfRjUunaJf2ow==</ds:X509Certificate> +				</ds:X509Data> +			</ds:KeyInfo> +		</md:KeyDescriptor> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat> +		<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat> +		<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://vidp.gv.at/ms_connector/pvp/post"/> +		<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://vidp.gv.at/ms_connector/pvp/redirect"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CCS-URL" Name="urn:oid:1.2.40.0.10.2.1.1.261.64" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN" Name="urn:oid:1.2.40.0.10.2.1.1.261.36" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SIGNER-CERTIFICATE" Name="urn:oid:1.2.40.0.10.2.1.1.261.66" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SECTOR-FOR-IDENTIFIER" Name="urn:oid:1.2.40.0.10.2.1.1.261.34" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-SOURCE-PIN-TYPE" Name="urn:oid:1.2.40.0.10.2.1.1.261.104" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-E-ID-TOKEN" Name="urn:oid:1.2.40.0.10.2.1.1.261.39" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-LINK" Name="urn:oid:1.2.40.0.10.2.1.1.261.38" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +		<saml2:Attribute xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" FriendlyName="EID-IDENTITY-STATUS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.109" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"/> +	</md:IDPSSODescriptor> +</md:EntityDescriptor>
\ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/pvp_postbinding_template.html b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/pvp_postbinding_template.html new file mode 100644 index 00000000..68a797e6 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/pvp_postbinding_template.html @@ -0,0 +1,3 @@ +#if($RelayState)RelayState=${RelayState}#end +#if($SAMLRequest)SAMLRequest=${SAMLRequest}#end +#if($SAMLResponse)SAMLResponse=${SAMLResponse}#end diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/sp_metadata_junit.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/sp_metadata_junit.xml new file mode 100644 index 00000000..0e25cce4 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/data/sp_metadata_junit.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="UTF-8"?> +<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="_1a48ec3432f2f3ba6222724a5b06f873" entityID="https://localhost/authhandler/sp/idaustria/metadata" validUntil="2045-02-06T08:47:26.211Z"> +    <md:SPSSODescriptor AuthnRequestsSigned="true" WantAssertionsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> +        <md:KeyDescriptor use="signing"> +            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +                <ds:X509Data> +                    <ds:X509Certificate>MIIC+DCCAeCgAwIBAgIEXh7TbTANBgkqhkiG9w0BAQsFADA+MQswCQYDVQQGEwJBVDENMAsGA1UE +                        CgwERUdJWjEOMAwGA1UECwwFalVuaXQxEDAOBgNVBAMMB3NpZ25pbmcwHhcNMjAwMTE1MDg1NTA5 +                        WhcNMjkwMTE0MDg1NTA5WjA+MQswCQYDVQQGEwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwF +                        alVuaXQxEDAOBgNVBAMMB3NpZ25pbmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCU +                        SiRjnDvPafZfhJ+L1wM86FKJX3VIAV/8TD9qJ6HOBkn5WwYfpheyCfRb6XVDyIGpO8qnMWAgC17N +                        gbmhzj8d8HXNQ2l3uppMv24oUTfXyYhQfZWAghx0sTlRIx/ZmlnduJilx2S53Sa7ruJwlQcBFXj9 +                        h9B8dtyegc86Sx6D9BumP1xU7+mEBk8Gv9rR5Khg0Y7qGfZWB0t4aikgaupWveVwiGifOOSfR8cz +                        qIg9qUpMYfZiTEBTSRmN6sPiNWhd4J0GyAI9Rn5C9jz/sSlQrxpN+4DXzsqSU5F6gzq3yRux6wyO +                        zDlt2birf21VPQ9HIy4YCjZXwgDWG7AO821pAgMBAAEwDQYJKoZIhvcNAQELBQADggEBADnwdaxU +                        tQU6SIpYwIb2c0ljTmQi7ryUcUpNHtK0M0E5Mw5Ex8zwrWbNQZ2sUyc4r07M66iOIqHsYZUQlRYv +                        VKHifDpAr8TCgD7iGGdB3By8Ou0RaNW+03w1fwmi98CufbHCGvpv0o2KxlejoHZminNdQ79ibN+0 +                        1nhocezJQATEQlnwHLiQSjilXpZeLYDk8HbrcUXNRxezN4ChdH+uU54vf+Uxqcj9QHcmBe1+BM8E +                        XfqS1DbTwZl+NTCnh5OYl8fvIFSOHMBxwFrI4pyY0faxg9UcrCogn/oQ+mV1gnVUDaDhvvEnVGZQ +                        trlt7heVId2BeNellVgsrcmdW8j4U9U=</ds:X509Certificate> +                </ds:X509Data> +            </ds:KeyInfo> +        </md:KeyDescriptor> +        <md:KeyDescriptor use="encryption"> +            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> +                <ds:X509Data> +                    <ds:X509Certificate>MIIDKzCCAhMCBFrxKO4wDQYJKoZIhvcNAQELBQAwWjELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVH +                        SVoxGDAWBgNVBAsMD2RlbW8uZWdpei5ndi5hdDEiMCAGA1UEAwwZTU9BLUlEIElEUCAoVGVzdC1W +                        ZXJzaW9uKTAeFw0xODA1MDgwNDM0NTRaFw0yMTAxMzEwNDM0NTRaMFoxCzAJBgNVBAYTAkFUMQ0w +                        CwYDVQQKDARFR0laMRgwFgYDVQQLDA9kZW1vLmVnaXouZ3YuYXQxIjAgBgNVBAMMGU1PQS1JRCBJ +                        RFAgKFRlc3QtVmVyc2lvbikwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCaFnqoaYoq +                        UptenemC6FiVDg5F2hEjpjix8+ow6/6QhUl2cPOS0uwZHaIvwT/RVbJ9CPdil6+11qaCPfZ+FoY+ +                        M+ke7TRd2RS1DqFbe1KC0imEnwemyLQrYe5Pm7DNcaY/kHTTq+k0eeGbYH0U/Iopyi0VuN5OWl4F +                        Vg45pf7knhXkaimItdjnCXnKcYM91mmltCf6TDgUrz7US7PmgvinnhfBgdITAT4GRr4ehliT+/jt +                        1OzHEyWRHanBGIpXNeZNqxgnpnGtaDh4JZuYR8qfH+GRK6dtW2ziej6rGIiUElGVCkXsohgxMNzq +                        nWeD9JT8+yyp1XZlyQf+IxhhESQLAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAIFejAFQepaEl/kC +                        VLvidMR+MXq5LCGHthUiI6eDTQZ+H7lZdHlj547XwEdX15b6Md3h7eSJ4hwlfV4go/0FaoLPzvVq +                        itwtYY5htywB3B6ZV34Eyi6C59Gl34XrV8CWxH4KKwLsVAjAy+/p/Xh0q2pzSBkeOChzBMBkjmyc +                        2Ue4MEKdL9guzp6+Yc/HL/phHAKYapkVyFwvsdqWOgyRzxAHINko8ExImMMB3xB5a52kfqLcui5O +                        fzEhjwLFJaGBMmFCmFGGOUwtIvl/6ZQ2LLzOE9+giVK9WsIgH11Pu+ejPFAbXf8cf4oWhbAfTkiy +                        4jpXrp77JXFRSDWddb0yePc=</ds:X509Certificate> +                </ds:X509Data> +            </ds:KeyInfo> +        </md:KeyDescriptor> +        <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat> +        <md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/post" index="0" isDefault="true"/> +        <md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/redirect" index="1"/> +        <md:AttributeConsumingService index="0" isDefault="true"> +            <md:ServiceName xml:lang="en">Default Service</md:ServiceName> +            <md:RequestedAttribute FriendlyName="BPK" Name="urn:oid:1.2.40.0.10.2.1.1.149" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +            <md:RequestedAttribute FriendlyName="PRINCIPAL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.20" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +            <md:RequestedAttribute FriendlyName="BIRTHDATE" Name="urn:oid:1.2.40.0.10.2.1.1.55" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +            <md:RequestedAttribute FriendlyName="PVP-VERSION" Name="urn:oid:1.2.40.0.10.2.1.1.261.10" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +            <md:RequestedAttribute FriendlyName="EID-ISSUING-NATION" Name="urn:oid:1.2.40.0.10.2.1.1.261.32" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +            <md:RequestedAttribute FriendlyName="MANDATOR-LEGAL-PERSON-SOURCE-PIN-TYPE" Name="urn:oid:1.2.40.0.10.2.1.1.261.76" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="false"/> +            <md:RequestedAttribute FriendlyName="MANDATOR-LEGAL-PERSON-FULL-NAME" Name="urn:oid:1.2.40.0.10.2.1.1.261.84" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="false"/> +            <md:RequestedAttribute FriendlyName="MANDATE-TYPE" Name="urn:oid:1.2.40.0.10.2.1.1.261.68" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="false"/> +            <md:RequestedAttribute FriendlyName="MANDATOR-LEGAL-PERSON-SOURCE-PIN" Name="urn:oid:1.2.40.0.10.2.1.1.261.100" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="false"/> +            <md:RequestedAttribute FriendlyName="GIVEN-NAME" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +            <md:RequestedAttribute FriendlyName="EID-SECTOR-FOR-IDENTIFIER" Name="urn:oid:1.2.40.0.10.2.1.1.261.34" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +            <md:RequestedAttribute FriendlyName="MANDATE-TYPE-OID" Name="urn:oid:1.2.40.0.10.2.1.1.261.106" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="false"/> +            <md:RequestedAttribute FriendlyName="EID-IDENTITY-LINK" Name="urn:oid:1.2.40.0.10.2.1.1.261.38" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="false"/> +            <md:RequestedAttribute FriendlyName="EID-CITIZEN-QAA-EIDAS-LEVEL" Name="urn:oid:1.2.40.0.10.2.1.1.261.108" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/> +        </md:AttributeConsumingService> +    </md:SPSSODescriptor> +</md:EntityDescriptor> diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/junit_test.jks b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/junit_test.jksBinary files differ new file mode 100644 index 00000000..ee6254a9 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/junit_test.jks diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/pvp.p12 b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/pvp.p12Binary files differ new file mode 100644 index 00000000..183342f7 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/keystore/pvp.p12 | 
