From 5649772eedcb67d79ebb95e2074455bef6d3ba56 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Thu, 3 Dec 2020 10:13:44 +0100 Subject: general workflow steps 1-8 --- .../modules/auth/eidas/v2/test/EidasRequestPreProcessingSecondTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasRequestPreProcessingSecondTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasRequestPreProcessingSecondTest.java index da7e3d85..e7bacded 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasRequestPreProcessingSecondTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/EidasRequestPreProcessingSecondTest.java @@ -107,7 +107,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()); -- cgit v1.2.3 From d1c4bc0619b95564f6f7db5798479449e88e4793 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Wed, 9 Dec 2020 08:53:28 +0100 Subject: added (non working) test --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 160 +++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java new file mode 100644 index 00000000..30f88ec8 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -0,0 +1,160 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import 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.protocol.impl.AuthenticationResponse; +import lombok.val; +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.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.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; + +@RunWith(SpringJUnit4ClassRunner.class) +//@RunWith(PowerMockRunner.class) +//@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/SpringTest-context_tasks_test.xml") +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) +//@RunWith(PowerMockRunner.class) +//@PrepareForTest(InitialSearchTaskFirstTest.class) +public class InitialSearchTaskFirstTest { + + @Autowired(required = true) + @Mock + private InitialSearchTask task; + + @Autowired(required = true) + private IConfiguration basicConfig; + + final ExecutionContext executionContext = new ExecutionContextImpl(); + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private TestRequestImpl pendingReq; + private DummySpConfiguration oaParam; + + /** + * jUnit class initializer. + * + * @throws IOException In case of an error + */ + @BeforeClass + public static void classInitializer() throws IOException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/junit_config_1.properties"); + + } + + /** + * jUnit test set-up. + * + */ + @Before + public void setUp() throws URISyntaxException, EaafStorageException { + + task = PowerMockito.spy(task); + + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + final AuthenticationResponse response = buildDummyAuthResponse(); + pendingReq = new TestRequestImpl(); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + + } + + @Test + @DirtiesContext + public void testInitialSearch() throws Exception { + + try { + task.execute(pendingReq, executionContext); + + } catch (final TaskExecutionException e) { + // forward URL is not set in example config + // org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e.getOriginalException(), + // "Wrong exception"); + // Assert.assertEquals("wrong errorCode", "config.08", ((EaafException) e.getOriginalException()) + // .getErrorId()); + // Assert.assertEquals("wrong parameter size", 1, ((EaafException) e.getOriginalException()) + // .getParams().length); + // Assert.assertEquals("wrong errorMsg", Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL, ((EaafException) e + // .getOriginalException()).getParams()[0]); + + } +// verifyPrivate(task, times(1)).invoke("step2", ArgumentMatchers.any(SimpleEidasData.class)); +// verifyPrivate(task, times(0)).invoke("step3", ArgumentMatchers.any()); +// verifyPrivate(task, times(0)).invoke("step4", ArgumentMatchers.any()); + + } + + + @NotNull + private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { + final AttributeDefinition attributeDef = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef2 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME).nameUri(new URI("ad", "sd", "fff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "aff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef3 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME).nameUri(new URI("ad", "sd", "ffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef4 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH).nameUri(new URI("ad", "sd", "fffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); + + final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder() + .put(attributeDef, "de/st/" + RandomStringUtils.randomNumeric(64)) + .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) + .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)).put(attributeDef4, "2001-01-01").build(); + + val b = new AuthenticationResponse.Builder(); + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf") + .attributes(attributeMap).build(); + } +} -- cgit v1.2.3 From f31d767bf6b8a92f7b05e030c26e43ad71cc0f20 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 11 Dec 2020 17:16:50 +0100 Subject: added two tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 135 +++++++++++++++------ 1 file changed, 96 insertions(+), 39 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 30f88ec8..1b1bdeae 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -1,10 +1,13 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.RegisterResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.DummyErnbClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.DummyZmrClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; 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; @@ -23,12 +26,10 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -38,30 +39,29 @@ 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 org.junit.Assert; import javax.xml.namespace.QName; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; - -import static org.mockito.Mockito.times; -import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import java.util.ArrayList; @RunWith(SpringJUnit4ClassRunner.class) -//@RunWith(PowerMockRunner.class) -//@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) + @ContextConfiguration("/SpringTest-context_tasks_test.xml") @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) -//@RunWith(PowerMockRunner.class) -//@PrepareForTest(InitialSearchTaskFirstTest.class) public class InitialSearchTaskFirstTest { @Autowired(required = true) @Mock + @InjectMocks private InitialSearchTask task; - @Autowired(required = true) - private IConfiguration basicConfig; + @Mock + private IZmrClient zmrClient; + + @Mock + private IErnbClient ernbClient; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -71,7 +71,7 @@ public class InitialSearchTaskFirstTest { /** * jUnit class initializer. - * + * * @throws IOException In case of an error */ @BeforeClass @@ -84,7 +84,6 @@ public class InitialSearchTaskFirstTest { /** * jUnit test set-up. - * */ @Before public void setUp() throws URISyntaxException, EaafStorageException { @@ -96,41 +95,97 @@ public class InitialSearchTaskFirstTest { RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - final AuthenticationResponse response = buildDummyAuthResponse(); + final AuthenticationResponse response = buildDummyAuthResponseMaxMustermann(); pendingReq = new TestRequestImpl(); pendingReq.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); } - + @Test @DirtiesContext - public void testInitialSearch() throws Exception { + /** + * Two matches found in ZMR + */ + public void testNode101a() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); try { task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); } catch (final TaskExecutionException e) { - // forward URL is not set in example config - // org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e.getOriginalException(), - // "Wrong exception"); - // Assert.assertEquals("wrong errorCode", "config.08", ((EaafException) e.getOriginalException()) - // .getErrorId()); - // Assert.assertEquals("wrong parameter size", 1, ((EaafException) e.getOriginalException()) - // .getParams().length); - // Assert.assertEquals("wrong errorMsg", Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL, ((EaafException) e - // .getOriginalException()).getParams()[0]); - + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } -// verifyPrivate(task, times(1)).invoke("step2", ArgumentMatchers.any(SimpleEidasData.class)); -// verifyPrivate(task, times(0)).invoke("step3", ArgumentMatchers.any()); -// verifyPrivate(task, times(0)).invoke("step4", ArgumentMatchers.any()); + } + + + @Test + @DirtiesContext + /** + * Two matches found in ErnB + */ + public void testNode101b() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + } catch (final TaskExecutionException e) { + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } } @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { + return buildDummyAuthResponse(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + "de/st/" + RandomStringUtils.randomNumeric(64), "2001-01-01"); + } + + @NotNull + private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { + return buildDummyAuthResponse("Max", "Mustermann", + "de/st/max123", "1111-01-01"); + } + + @NotNull + private AuthenticationResponse buildDummyAuthResponse(String givenName, String familyName, String identifier, + String dateOfBirth) throws URISyntaxException { final AttributeDefinition attributeDef = AttributeDefinition.builder() .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) @@ -149,12 +204,14 @@ public class InitialSearchTaskFirstTest { .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder() - .put(attributeDef, "de/st/" + RandomStringUtils.randomNumeric(64)) - .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) - .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)).put(attributeDef4, "2001-01-01").build(); + .put(attributeDef, identifier) + .put(attributeDef2, familyName) + .put(attributeDef3, givenName) + .put(attributeDef4, dateOfBirth).build(); val b = new AuthenticationResponse.Builder(); - return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf") + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( + "afaf") .attributes(attributeMap).build(); } } -- cgit v1.2.3 From 75c403b2067dac3ccafae3b751f8714ebff342fa Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Tue, 15 Dec 2020 23:07:53 +0100 Subject: added machting (3-4) + tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 140 ++++++++++++++++++++- 1 file changed, 136 insertions(+), 4 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 1b1bdeae..2614f9ba 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -111,8 +111,8 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); - zmrResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); @@ -151,8 +151,8 @@ public class InitialSearchTaskFirstTest { //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); - ernbResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -170,6 +170,138 @@ public class InitialSearchTaskFirstTest { } } + @Test + @DirtiesContext + /** + * One match, but register update needed + */ + public void testNode100a() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + String randomBpk = RandomStringUtils.randomNumeric(6); + zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); + + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * One match, but register update needed + */ + public void testNode100b() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + String randomBpk = RandomStringUtils.randomNumeric(6); + ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * One match, no register update needed + */ + public void testNode102a() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * One match, no register update needed + */ + public void testNode102b() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { -- cgit v1.2.3 From 3b34f664d0838ff9fb1764fb58813dd6ea83b1df Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Tue, 15 Dec 2020 23:57:14 +0100 Subject: Testcase no match found added --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 2614f9ba..924a180d 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -303,6 +303,38 @@ public class InitialSearchTaskFirstTest { } } + + @Test + @DirtiesContext + /** + * NO match found in ZMR and ErnB with Initial search + */ + public void testNode105() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("105")); + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { return buildDummyAuthResponse(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -- cgit v1.2.3 From f0ec2ed628eeb8e020919f3f719ee633ae05806f Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Wed, 16 Dec 2020 17:32:43 +0100 Subject: 2 more tests (bean mocking still missing) --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 85 +++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 924a180d..5c75d1e4 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -22,8 +22,10 @@ import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; import lombok.val; import org.apache.commons.lang3.RandomStringUtils; import org.jetbrains.annotations.NotNull; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -39,7 +41,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import org.junit.Assert; + import javax.xml.namespace.QName; import java.io.IOException; import java.net.URI; @@ -303,6 +305,87 @@ public class InitialSearchTaskFirstTest { } } + @Ignore + @Test + @DirtiesContext + /** + * One match found in ZMR and ErnB with detail search + */ + public void testNode103() throws Exception { + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, + // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address + zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, + "tax123", null)); + + Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Ignore + @Test + @DirtiesContext + /** + * Multiple matches found in ZMR and ErnB with detail search + */ + public void testNode104() throws Exception { + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, + // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address + zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, + "tax123", null)); + zmrResultSpecific.add(new RegisterResult("bpkMax1","de/st/max1235", "Max", "Mustermann", "1111-01-01", null, null, + "tax123", null)); + Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + + + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + + } catch (final TaskExecutionException e) { + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + } + @Test @DirtiesContext -- cgit v1.2.3 From a1cffbe51cccef6b0cd7e238c384ac7f51ecb27f Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Thu, 17 Dec 2020 13:18:37 +0100 Subject: country specific tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 305 +++++++++++++++++---- 1 file changed, 251 insertions(+), 54 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 5c75d1e4..64a73bda 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -5,6 +5,9 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.RegisterResult; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.DummyErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ICountrySpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.DummyZmrClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; @@ -25,7 +28,6 @@ import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -47,6 +49,7 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; +import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @@ -107,54 +110,55 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Two matches found in ZMR + * One match, but register update needed */ - public void testNode101a() throws Exception { + public void testNode100a() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + String randomBpk = RandomStringUtils.randomNumeric(6); + zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? task.setErnbClient(ernbClient); try { task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong workflow, should not reach this point", false); } } - @Test @DirtiesContext /** - * Two matches found in ErnB + * One match, but register update needed */ - public void testNode101b() throws Exception { + public void testNode100b() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + String randomBpk = RandomStringUtils.randomNumeric(6); + ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -162,68 +166,67 @@ public class InitialSearchTaskFirstTest { try { task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong workflow, should not reach this point", false); } } + @Test @DirtiesContext /** - * One match, but register update needed + * Two matches found in ZMR */ - public void testNode100a() throws Exception { + public void testNode101a() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - String randomBpk = RandomStringUtils.randomNumeric(6); - zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); - + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? task.setErnbClient(ernbClient); try { task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } } + @Test @DirtiesContext /** - * One match, but register update needed + * Two matches found in ErnB */ - public void testNode100b() throws Exception { + public void testNode101b() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - String randomBpk = RandomStringUtils.randomNumeric(6); - ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -231,12 +234,13 @@ public class InitialSearchTaskFirstTest { try { task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } } @@ -255,7 +259,7 @@ public class InitialSearchTaskFirstTest { //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -281,7 +285,7 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? @@ -305,13 +309,18 @@ public class InitialSearchTaskFirstTest { } } - @Ignore @Test @DirtiesContext /** * One match found in ZMR and ErnB with detail search */ - public void testNode103() throws Exception { + public void testNode103IT() throws Exception { + String bpkRegister = "bpkMax"; + String taxNumber = "tax123"; + final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(taxNumber); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); @@ -320,10 +329,10 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResultSpecific = new ArrayList<>(); //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, - "tax123", null)); + zmrResultSpecific.add(new RegisterResult(bpkRegister,"it/st/max1234", "Max", "Mustermann", "2011-01-01", null, + null, taxNumber, null)); - Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); task.setZmrClient(zmrClient); //Mock ernb initial search @@ -333,24 +342,160 @@ public class InitialSearchTaskFirstTest { task.setErnbClient(ernbClient); + //Mock country specific search + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); + it.setErnbClient(ernbClient); + it.setZmrClient(zmrClient); + handlers.add(it); + task.setHandlers(handlers); + try { - task.execute(pendingReq, executionContext); + task.execute(pendingReq1, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(bpkRegister)); + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * Multiple matches found in ZMR and ErnB with detail search + */ + public void testNode103DE() throws Exception { + String givenName = "Max"; + String familyName = "Mustermann"; + String pseudonym = "de/st/max1234"; + String bpk = "bpkMax"; + String dateOfBirth = "2011-01-01"; + String placeOfBirth = "München"; + String birthName = "BabyMax"; + final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym, + dateOfBirth, placeOfBirth, birthName); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + + zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + null, null)); + + //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), + // eidData.getPlaceOfBirth(), eidData.getBirthName() + Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + //Mock country specific search + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); + de.setErnbClient(ernbClient); + de.setZmrClient(zmrClient); + handlers.add(de); + task.setHandlers(handlers); + + try { + task.execute(pendingReq1, executionContext); + + String bPk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(bpk)); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); } } - @Ignore @Test @DirtiesContext /** * Multiple matches found in ZMR and ErnB with detail search */ - public void testNode104() throws Exception { + public void testNode104DE() throws Exception { + String givenName = "Max"; + String familyName = "Mustermann"; + String pseudonym1 = "de/st/max1234"; + String pseudonym2 = "de/st/max12345"; + String bpk1 = "bpkMax"; + String bpk2 = "bpkMax1"; + String dateOfBirth = "2011-01-01"; + String placeOfBirth = "München"; + String birthName = "BabyMax"; + final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym1, + dateOfBirth, placeOfBirth, birthName); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + + zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + null, null)); + zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + null, null)); + //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), + // eidData.getPlaceOfBirth(), eidData.getBirthName() + Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + //Mock country specific search + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); + de.setErnbClient(ernbClient); + de.setZmrClient(zmrClient); + handlers.add(de); + task.setHandlers(handlers); + + try { + task.execute(pendingReq1, executionContext); + + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + + } catch (final TaskExecutionException e) { + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + } + + @Test + @DirtiesContext + /** + * Multiple matches found in ZMR and ErnB with detail search + */ + public void testNode104IT() throws Exception { + + String fakeTaxNumber = "tax123"; + final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(fakeTaxNumber); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); @@ -359,11 +504,11 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResultSpecific = new ArrayList<>(); //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, - "tax123", null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1","de/st/max1235", "Max", "Mustermann", "1111-01-01", null, null, - "tax123", null)); - Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + zmrResultSpecific.add(new RegisterResult("bpkMax","it/st/max1234", "Max", "Mustermann", "2011-01-01", null, null, + fakeTaxNumber, null)); + zmrResultSpecific.add(new RegisterResult("bpkMax1","it/st/max1235", "Max", "Mustermann", "2011-01-01", null, null, + fakeTaxNumber, null)); + Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); task.setZmrClient(zmrClient); @@ -375,8 +520,16 @@ public class InitialSearchTaskFirstTest { task.setErnbClient(ernbClient); + //Mock country specific search + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); + it.setErnbClient(ernbClient); + it.setZmrClient(zmrClient); + handlers.add(it); + task.setHandlers(handlers); + try { - task.execute(pendingReq, executionContext); + task.execute(pendingReq1, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -386,7 +539,6 @@ public class InitialSearchTaskFirstTest { } } - @Test @DirtiesContext /** @@ -427,12 +579,35 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { return buildDummyAuthResponse("Max", "Mustermann", - "de/st/max123", "1111-01-01"); + "de/st/max123", "2011-01-01"); + } + + private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT() throws URISyntaxException { + return buildDummyAuthResponse("Max", "Mustermann", + "it/st/max123", "2011-01-01"); + } + + private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT_Tax(String taxNumber) throws URISyntaxException { + return buildDummyAuthResponse("Max", "Mustermann", + "it/st/max123", "2011-01-01", taxNumber, null, null); } @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 { final AttributeDefinition attributeDef = AttributeDefinition.builder() .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) @@ -449,12 +624,34 @@ public class InitialSearchTaskFirstTest { .friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH).nameUri(new URI("ad", "sd", "fffff")) .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affff")) .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); - - final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder() + final AttributeDefinition attributeDef5 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_TAXREFERENCE).nameUri(new URI("ad", "sd", "ffffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef6 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_PLACEOFBIRTH).nameUri(new URI("ad", "sd", "fffffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affffff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef7 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_BIRTHNAME).nameUri(new URI("ad", "sd", "ffffffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffffff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() .put(attributeDef, identifier) .put(attributeDef2, familyName) .put(attributeDef3, givenName) - .put(attributeDef4, dateOfBirth).build(); + .put(attributeDef4, dateOfBirth); + + if(taxNumber != null) { + builder.put(attributeDef5, taxNumber); + } + if(birthName != null) { + builder.put(attributeDef7, birthName); + } + if(placeOfBirth != null) { + builder.put(attributeDef6, placeOfBirth); + } + final ImmutableAttributeMap attributeMap = builder.build(); val b = new AuthenticationResponse.Builder(); return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( -- cgit v1.2.3 From 06d395c2102cf6a8bb961ac6bb2113c12eda9651 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Fri, 18 Dec 2020 10:22:59 +0100 Subject: Review code --- .../eidas/v2/test/tasks/InitialSearchTaskFirstTest.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 64a73bda..d366fefc 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -62,9 +62,11 @@ public class InitialSearchTaskFirstTest { @InjectMocks private InitialSearchTask task; + // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? @Mock private IZmrClient zmrClient; + // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? @Mock private IErnbClient ernbClient; @@ -92,7 +94,7 @@ public class InitialSearchTaskFirstTest { */ @Before public void setUp() throws URISyntaxException, EaafStorageException { - + // NOTE: PowerMockito should not be needed, as we don't want to test static and private methods task = PowerMockito.spy(task); httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); @@ -112,6 +114,7 @@ public class InitialSearchTaskFirstTest { /** * One match, but register update needed */ + // NOTE: Why is the method named "testNode100a"? public void testNode100a() throws Exception { //Mock ZMR @@ -119,6 +122,9 @@ public class InitialSearchTaskFirstTest { String randomBpk = RandomStringUtils.randomNumeric(6); zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + // NOTE: Are we using Mockito or these fixed strings in DummyZmrClient? + // NOTE: Please mock an interface, not a concrete class + // NOTE: But DummyZmrClient is also defined as a bean "ZmrClientForeIDAS" in "eidas_v2_auth.beans.xml"? zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); @@ -137,11 +143,13 @@ public class InitialSearchTaskFirstTest { Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { + // NOTE: assertTrue is probably the wrong method to use ... why catch the exception anyway? Assert.assertTrue("Wrong workflow, should not reach this point", false); } } @Test + // NOTE: Why is @DirtiesContext after each test necessary? What is changed in the context and why? @DirtiesContext /** * One match, but register update needed @@ -563,6 +571,7 @@ public class InitialSearchTaskFirstTest { String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + // NOTE: Why "105"? Extract in a constant Assert.assertTrue("Wrong bpk", bPk.equals("105")); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); @@ -578,6 +587,8 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { + // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string again? + // NOTE: If not, why not using random strings? return buildDummyAuthResponse("Max", "Mustermann", "de/st/max123", "2011-01-01"); } -- cgit v1.2.3 From 2bf0a3cb7413846b8349cf53904588994ed117af Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 18 Dec 2020 17:24:55 +0100 Subject: constructor based injection, randomized values for testing, added constants --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 289 ++++++++------------- 1 file changed, 115 insertions(+), 174 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index d366fefc..f7fc6b06 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -2,20 +2,17 @@ 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.RegisterResult; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.DummyErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ICountrySpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.DummyZmrClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; import eu.eidas.auth.commons.attribute.AttributeDefinition; @@ -33,7 +30,6 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -62,20 +58,16 @@ public class InitialSearchTaskFirstTest { @InjectMocks private InitialSearchTask task; - // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? - @Mock private IZmrClient zmrClient; - - // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? - @Mock private IErnbClient ernbClient; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; private MockHttpServletResponse httpResp; private TestRequestImpl pendingReq; - private DummySpConfiguration oaParam; - + private String randomIdentifier = RandomStringUtils.randomNumeric(10); + private String randomFamilyName = RandomStringUtils.randomNumeric(11); + private String randomGivenName = RandomStringUtils.randomNumeric(12); /** * jUnit class initializer. * @@ -86,7 +78,6 @@ public class InitialSearchTaskFirstTest { final String current = new java.io.File(".").toURI().toString(); System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_1.properties"); - } /** @@ -94,19 +85,15 @@ public class InitialSearchTaskFirstTest { */ @Before public void setUp() throws URISyntaxException, EaafStorageException { - // NOTE: PowerMockito should not be needed, as we don't want to test static and private methods - task = PowerMockito.spy(task); - httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - final AuthenticationResponse response = buildDummyAuthResponseMaxMustermann(); + final AuthenticationResponse response = buildDummyAuthResponseRandomPerson(); pendingReq = new TestRequestImpl(); pendingReq.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - } @Test @@ -120,22 +107,18 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); - // NOTE: Are we using Mockito or these fixed strings in DummyZmrClient? - // NOTE: Please mock an interface, not a concrete class - // NOTE: But DummyZmrClient is also defined as a bean "ZmrClientForeIDAS" in "eidas_v2_auth.beans.xml"? - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) @@ -159,19 +142,18 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult);//"de/st/max123"??? //Mock ernb ArrayList ernbResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) @@ -193,24 +175,20 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -227,25 +205,21 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -259,26 +233,25 @@ public class InitialSearchTaskFirstTest { */ public void testNode102a() throws Exception { + String randomBpk = RandomStringUtils.randomNumeric(12);; //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); - + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); } @@ -290,27 +263,26 @@ public class InitialSearchTaskFirstTest { * One match, no register update needed */ public void testNode102b() throws Exception { - + String randomBpk = RandomStringUtils.randomNumeric(14); //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); @@ -323,40 +295,36 @@ public class InitialSearchTaskFirstTest { * One match found in ZMR and ErnB with detail search */ public void testNode103IT() throws Exception { - String bpkRegister = "bpkMax"; - String taxNumber = "tax123"; - final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(taxNumber); + String bpkRegister = RandomStringUtils.randomNumeric(14); + String taxNumber = RandomStringUtils.randomNumeric(14); + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult(bpkRegister,"it/st/max1234", "Max", "Mustermann", "2011-01-01", null, - null, taxNumber, null)); + zmrResultSpecific.add(new RegisterResult(bpkRegister, "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, + "2011-01-01", null, null, taxNumber, null)); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); - task.setZmrClient(zmrClient); //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); - task.setErnbClient(ernbClient); //Mock country specific search List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); - it.setErnbClient(ernbClient); - it.setZmrClient(zmrClient); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(it); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -375,8 +343,8 @@ public class InitialSearchTaskFirstTest { * Multiple matches found in ZMR and ErnB with detail search */ public void testNode103DE() throws Exception { - String givenName = "Max"; - String familyName = "Mustermann"; + String givenName = randomGivenName; + String familyName = randomFamilyName; String pseudonym = "de/st/max1234"; String bpk = "bpkMax"; String dateOfBirth = "2011-01-01"; @@ -390,33 +358,26 @@ public class InitialSearchTaskFirstTest { //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, + birthName, null, null)); - //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), - // eidData.getPlaceOfBirth(), eidData.getBirthName() Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - task.setZmrClient(zmrClient); - //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? - - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); //Mock country specific search List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); - de.setErnbClient(ernbClient); - de.setZmrClient(zmrClient); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(de); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -435,8 +396,8 @@ public class InitialSearchTaskFirstTest { * Multiple matches found in ZMR and ErnB with detail search */ public void testNode104DE() throws Exception { - String givenName = "Max"; - String familyName = "Mustermann"; + String givenName = randomGivenName; + String familyName = randomFamilyName; String pseudonym1 = "de/st/max1234"; String pseudonym2 = "de/st/max12345"; String bpk1 = "bpkMax"; @@ -452,34 +413,29 @@ public class InitialSearchTaskFirstTest { //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, + birthName, null, null)); - zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, + birthName, null, null)); - //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), - // eidData.getPlaceOfBirth(), eidData.getBirthName() Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - task.setZmrClient(zmrClient); //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? - - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); //Mock country specific search List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); - de.setErnbClient(ernbClient); - de.setZmrClient(zmrClient); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(de); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -498,43 +454,34 @@ public class InitialSearchTaskFirstTest { * Multiple matches found in ZMR and ErnB with detail search */ public void testNode104IT() throws Exception { - - String fakeTaxNumber = "tax123"; - final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(fakeTaxNumber); + String fakeTaxNumber = RandomStringUtils.randomNumeric(14);; + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, - // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult("bpkMax","it/st/max1234", "Max", "Mustermann", "2011-01-01", null, null, + + zmrResultSpecific.add(new RegisterResult("bpkMax", "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, "2011-01-01", null, null, fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1","it/st/max1235", "Max", "Mustermann", "2011-01-01", null, null, + zmrResultSpecific.add(new RegisterResult("bpkMax1", "it/st/"+randomIdentifier+"5", randomGivenName, randomFamilyName, "2011-01-01", null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - - task.setZmrClient(zmrClient); - //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? - - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); //Mock country specific search List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); - it.setErnbClient(ernbClient); - it.setZmrClient(zmrClient); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(it); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -552,27 +499,25 @@ public class InitialSearchTaskFirstTest { /** * NO match found in ZMR and ErnB with Initial search */ - public void testNode105() throws Exception { + public void testNode105() { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - // NOTE: Why "105"? Extract in a constant - Assert.assertTrue("Wrong bpk", bPk.equals("105")); + Assert.assertTrue("Wrong bpk", bPk.equals("TODO-Temporary-Endnode-105")); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); } @@ -580,27 +525,17 @@ public class InitialSearchTaskFirstTest { @NotNull - private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { - return buildDummyAuthResponse(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - "de/st/" + RandomStringUtils.randomNumeric(64), "2001-01-01"); - } - - @NotNull - private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { - // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string again? + private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { + // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string + // again? // NOTE: If not, why not using random strings? - return buildDummyAuthResponse("Max", "Mustermann", - "de/st/max123", "2011-01-01"); - } - - private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT() throws URISyntaxException { - return buildDummyAuthResponse("Max", "Mustermann", - "it/st/max123", "2011-01-01"); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, + "de/st/"+randomIdentifier, "2011-01-01"); } - private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT_Tax(String taxNumber) throws URISyntaxException { - return buildDummyAuthResponse("Max", "Mustermann", - "it/st/max123", "2011-01-01", taxNumber, null, null); + private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { + return buildDummyAuthResponse(randomGivenName, randomFamilyName, + "it/st/"+randomIdentifier, "2011-01-01", taxNumber, null, null); } @NotNull @@ -611,10 +546,11 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseDE(String givenName, String familyName, String identifier, - String dateOfBirth, String placeOfBirth, + 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, @@ -653,13 +589,13 @@ public class InitialSearchTaskFirstTest { .put(attributeDef3, givenName) .put(attributeDef4, dateOfBirth); - if(taxNumber != null) { + if (taxNumber != null) { builder.put(attributeDef5, taxNumber); } - if(birthName != null) { + if (birthName != null) { builder.put(attributeDef7, birthName); } - if(placeOfBirth != null) { + if (placeOfBirth != null) { builder.put(attributeDef6, placeOfBirth); } final ImmutableAttributeMap attributeMap = builder.build(); @@ -669,4 +605,9 @@ public class InitialSearchTaskFirstTest { "afaf") .attributes(attributeMap).build(); } + + private List emptyHandlers() { + return new ArrayList<>(); + } + } -- cgit v1.2.3 From 55d809e4b4df5c7ca9ba2bdf371f7f9376302ea8 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Thu, 7 Jan 2021 18:16:45 +0100 Subject: Resolve merge comments --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 438 +++++++++------------ 1 file changed, 197 insertions(+), 241 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index f7fc6b06..a1dce0f2 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -1,11 +1,34 @@ +/* + * 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.dao.RegisterResult; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ICountrySpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.CountrySpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; @@ -27,10 +50,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.Mockito; -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; @@ -46,6 +66,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; +import java.util.Random; @RunWith(SpringJUnit4ClassRunner.class) @@ -53,13 +74,9 @@ import java.util.List; @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskFirstTest { - @Autowired(required = true) - @Mock - @InjectMocks private InitialSearchTask task; - private IZmrClient zmrClient; - private IErnbClient ernbClient; + private IErnpClient ernpClient; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -68,6 +85,12 @@ public class InitialSearchTaskFirstTest { private String randomIdentifier = RandomStringUtils.randomNumeric(10); private String randomFamilyName = RandomStringUtils.randomNumeric(11); private String randomGivenName = RandomStringUtils.randomNumeric(12); + private String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); + private String randomBirthName = RandomStringUtils.randomNumeric(12); + private String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); + private String DE_ST = "de/st/"; + private String IT_ST = "it/st/"; + /** * jUnit class initializer. * @@ -101,68 +124,52 @@ public class InitialSearchTaskFirstTest { /** * One match, but register update needed */ - // NOTE: Why is the method named "testNode100a"? - public void testNode100a() throws Exception { + public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); + String newFirstName = RandomStringUtils.randomAlphabetic(5); + zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); - - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); - - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + ArrayList ernpResult = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - } catch (final TaskExecutionException e) { - // NOTE: assertTrue is probably the wrong method to use ... why catch the exception anyway? - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } @Test - // NOTE: Why is @DirtiesContext after each test necessary? What is changed in the context and why? @DirtiesContext /** * One match, but register update needed */ - public void testNode100b() throws Exception { + public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult);//"de/st/max123"??? + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); + ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); + ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } } @@ -171,21 +178,19 @@ public class InitialSearchTaskFirstTest { /** * Two matches found in ZMR */ - public void testNode101a() throws Exception { + public void testNode101_ManualFixNecessary_a() throws Exception { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); + zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ArrayList ernpResult = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -199,24 +204,24 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Two matches found in ErnB + * Two matches found in ErnP */ - public void testNode101b() throws Exception { - - //Mock ZMR + public void testNode101_ManualFixNecessary_b() throws Exception { + String randombpk = RandomStringUtils.random(5); ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); + ArrayList ernpResult = new ArrayList<>(); + ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), + randomFamilyName, + randomDate)); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -231,30 +236,24 @@ public class InitialSearchTaskFirstTest { /** * One match, no register update needed */ - public void testNode102a() throws Exception { + public void testNode102_UserIdentified_a() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(12);; - //Mock ZMR + String randomBpk = RandomStringUtils.randomNumeric(12); ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + ArrayList ernpResult = new ArrayList<>(); + ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } @Test @@ -262,39 +261,33 @@ public class InitialSearchTaskFirstTest { /** * One match, no register update needed */ - public void testNode102b() throws Exception { + public void testNode102_UserIdentified_b() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(14); - //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); + ArrayList ernpResult = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } @Test @DirtiesContext /** - * One match found in ZMR and ErnB with detail search + * One match found in ZMR and ErnP with detail search */ - public void testNode103IT() throws Exception { + public void testNode103_UserIdentified_IT() throws Exception { String bpkRegister = RandomStringUtils.randomNumeric(14); String taxNumber = RandomStringUtils.randomNumeric(14); final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); @@ -302,29 +295,26 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, - // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult(bpkRegister, "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, - "2011-01-01", null, null, taxNumber, null)); - Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); + zmrResultSpecific.add(new RegisterResult(bpkRegister, IT_ST+randomIdentifier+RandomStringUtils.random(2), + randomGivenName, + randomFamilyName, + randomDate, null, null, taxNumber, null)); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); + Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock country specific search - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(it); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -340,26 +330,25 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Multiple matches found in ZMR and ErnB with detail search + * Multiple matches found in ZMR and ErnP with detail search */ - public void testNode103DE() throws Exception { + public void testNode103_UserIdentified_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; - String pseudonym = "de/st/max1234"; - String bpk = "bpkMax"; - String dateOfBirth = "2011-01-01"; - String placeOfBirth = "München"; - String birthName = "BabyMax"; + String pseudonym = DE_ST + RandomStringUtils.random(5); + String bpk = RandomStringUtils.random(5); + String dateOfBirth = randomDate; + String placeOfBirth = randomPlaceOfBirth; + String birthName = randomBirthName; final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym, dateOfBirth, placeOfBirth, birthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, @@ -368,16 +357,14 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock country specific search - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(de); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -393,28 +380,27 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Multiple matches found in ZMR and ErnB with detail search + * Multiple matches found in ZMR and ErnP with detail search */ - public void testNode104DE() throws Exception { + public void testNode104_ManualFixNecessary_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; - String pseudonym1 = "de/st/max1234"; - String pseudonym2 = "de/st/max12345"; - String bpk1 = "bpkMax"; - String bpk2 = "bpkMax1"; - String dateOfBirth = "2011-01-01"; - String placeOfBirth = "München"; - String birthName = "BabyMax"; + String pseudonym1 = DE_ST + RandomStringUtils.random(5); + String pseudonym2 = pseudonym1 + RandomStringUtils.random(2); + String bpk1 = RandomStringUtils.random(5); + String bpk2 = bpk1 + RandomStringUtils.random(2); + String dateOfBirth = randomDate; + String placeOfBirth = randomPlaceOfBirth; + String birthName = randomBirthName; final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym1, dateOfBirth, placeOfBirth, birthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, @@ -425,23 +411,18 @@ public class InitialSearchTaskFirstTest { null, null)); Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); - - //Mock country specific search - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(de); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -451,43 +432,40 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Multiple matches found in ZMR and ErnB with detail search + * Multiple matches found in ZMR and ErnP with detail search */ - public void testNode104IT() throws Exception { + public void testNode104_ManualFixNecessary_IT() throws Exception { String fakeTaxNumber = RandomStringUtils.randomNumeric(14);; final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, "2011-01-01", null, null, + zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, + randomDate, null, null, fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1", "it/st/"+randomIdentifier+"5", randomGivenName, randomFamilyName, "2011-01-01", null, null, + zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, randomFamilyName, + randomDate, null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock country specific search - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(it); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -497,45 +475,35 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * NO match found in ZMR and ErnB with Initial search + * NO match found in ZMR and ErnP with Initial search */ - public void testNode105() { + public void testNode105_TemporaryEnd() throws TaskExecutionException { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); - - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); + ArrayList ernpResult = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("TODO-Temporary-Endnode-105")); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); } @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string - // again? - // NOTE: If not, why not using random strings? return buildDummyAuthResponse(randomGivenName, randomFamilyName, - "de/st/"+randomIdentifier, "2011-01-01"); + DE_ST+randomIdentifier, randomDate); } private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { return buildDummyAuthResponse(randomGivenName, randomFamilyName, - "it/st/"+randomIdentifier, "2011-01-01", taxNumber, null, null); + IT_ST+randomIdentifier, randomDate, taxNumber, null, null); } @NotNull @@ -555,58 +523,46 @@ public class InitialSearchTaskFirstTest { private AuthenticationResponse buildDummyAuthResponse(String givenName, String familyName, String identifier, String dateOfBirth, String taxNumber, String placeOfBirth, String birthName) throws URISyntaxException { - final AttributeDefinition attributeDef = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef2 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME).nameUri(new URI("ad", "sd", "fff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "aff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef3 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME).nameUri(new URI("ad", "sd", "ffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef4 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH).nameUri(new URI("ad", "sd", "fffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef5 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_TAXREFERENCE).nameUri(new URI("ad", "sd", "ffffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef6 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_PLACEOFBIRTH).nameUri(new URI("ad", "sd", "fffffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affffff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef7 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_BIRTHNAME).nameUri(new URI("ad", "sd", "ffffffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffffff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() - .put(attributeDef, identifier) - .put(attributeDef2, familyName) - .put(attributeDef3, givenName) - .put(attributeDef4, dateOfBirth); - + .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER,"ff","af"), identifier) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME,"fff","aff"), familyName) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME,"ffff","afff"), givenName) + .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH,"fffff","affff"), dateOfBirth); if (taxNumber != null) { - builder.put(attributeDef5, taxNumber); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE,"ffffff","afffff"), taxNumber); } if (birthName != null) { - builder.put(attributeDef7, birthName); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME,"fffffff","affffff"), birthName); } if (placeOfBirth != null) { - builder.put(attributeDef6, placeOfBirth); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH,"ffffffff","afffffff"), placeOfBirth); } final ImmutableAttributeMap attributeMap = builder.build(); val b = new AuthenticationResponse.Builder(); return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( - "afaf") - .attributes(attributeMap).build(); + "afaf").attributes(attributeMap).build(); + } + + private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + + ".LiteralStringAttributeValueMarshaller"); + } + + private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + + ".DateTimeAttributeValueMarshaller"); + } + + private AttributeDefinition 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(); } - private List emptyHandlers() { + private List emptyHandlers() { return new ArrayList<>(); } -- cgit v1.2.3 From b0f2b00b460e1c8419ea631bdbd1da1c33150bce Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 14:17:52 +0100 Subject: Streamline mock creation in tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 53 +++------------------- 1 file changed, 7 insertions(+), 46 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index a1dce0f2..12a0969d 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -50,7 +50,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.annotation.DirtiesContext; @@ -69,13 +71,14 @@ import java.util.List; import java.util.Random; @RunWith(SpringJUnit4ClassRunner.class) - @ContextConfiguration("/SpringTest-context_tasks_test.xml") @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskFirstTest { private InitialSearchTask task; + @Mock private IZmrClient zmrClient; + @Mock private IErnpClient ernpClient; final ExecutionContext executionContext = new ExecutionContextImpl(); @@ -108,6 +111,9 @@ public class InitialSearchTaskFirstTest { */ @Before public void setUp() throws URISyntaxException, EaafStorageException { + MockitoAnnotations.initMocks(this); + task = new InitialSearchTask(new ArrayList(), ernpClient, zmrClient); + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); @@ -125,20 +131,15 @@ public class InitialSearchTaskFirstTest { * One match, but register update needed */ public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); String newFirstName = RandomStringUtils.randomAlphabetic(5); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); - - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -151,20 +152,14 @@ public class InitialSearchTaskFirstTest { * One match, but register update needed */ public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -179,18 +174,14 @@ public class InitialSearchTaskFirstTest { * Two matches found in ZMR */ public void testNode101_ManualFixNecessary_a() throws Exception { - ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -209,7 +200,6 @@ public class InitialSearchTaskFirstTest { public void testNode101_ManualFixNecessary_b() throws Exception { String randombpk = RandomStringUtils.random(5); ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); @@ -217,11 +207,8 @@ public class InitialSearchTaskFirstTest { ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), randomFamilyName, randomDate)); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -237,19 +224,14 @@ public class InitialSearchTaskFirstTest { * One match, no register update needed */ public void testNode102_UserIdentified_a() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(12); ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -266,16 +248,11 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -296,7 +273,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -308,7 +284,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -347,7 +322,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -358,7 +332,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -399,7 +372,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -412,7 +384,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -442,7 +413,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -455,7 +425,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -478,16 +447,12 @@ public class InitialSearchTaskFirstTest { * NO match found in ZMR and ErnP with Initial search */ public void testNode105_TemporaryEnd() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -562,8 +527,4 @@ public class InitialSearchTaskFirstTest { .attributeValueMarshaller(marshaller).build(); } - private List emptyHandlers() { - return new ArrayList<>(); - } - } -- cgit v1.2.3 From 50c82048f034803a3486368d2c5cb3ad09eb07b3 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:00:43 +0100 Subject: Improve readability of test cases by using modern syntax --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 151 +++++++++------------ 1 file changed, 67 insertions(+), 84 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 12a0969d..35e2e56e 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -70,6 +70,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; +import static org.junit.Assert.assertThrows; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_tasks_test.xml") @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) @@ -82,17 +84,15 @@ public class InitialSearchTaskFirstTest { private IErnpClient ernpClient; final ExecutionContext executionContext = new ExecutionContextImpl(); - private MockHttpServletRequest httpReq; - private MockHttpServletResponse httpResp; private TestRequestImpl pendingReq; - private String randomIdentifier = RandomStringUtils.randomNumeric(10); - private String randomFamilyName = RandomStringUtils.randomNumeric(11); - private String randomGivenName = RandomStringUtils.randomNumeric(12); - private String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); - private String randomBirthName = RandomStringUtils.randomNumeric(12); - private String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); - private String DE_ST = "de/st/"; - private String IT_ST = "it/st/"; + private final String randomIdentifier = RandomStringUtils.randomNumeric(10); + private final String randomFamilyName = RandomStringUtils.randomNumeric(11); + private final String randomGivenName = RandomStringUtils.randomNumeric(12); + private final String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); + private final String randomBirthName = RandomStringUtils.randomNumeric(12); + private final String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); + private final String DE_ST = "de/st/"; + private final String IT_ST = "it/st/"; /** * jUnit class initializer. @@ -112,10 +112,10 @@ public class InitialSearchTaskFirstTest { @Before public void setUp() throws URISyntaxException, EaafStorageException { MockitoAnnotations.initMocks(this); - task = new InitialSearchTask(new ArrayList(), ernpClient, zmrClient); + task = new InitialSearchTask(new ArrayList<>(), ernpClient, zmrClient); - httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); - httpResp = new MockHttpServletResponse(); + MockHttpServletRequest httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + MockHttpServletResponse httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); @@ -125,11 +125,11 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); } - @Test - @DirtiesContext /** * One match, but register update needed */ + @Test + @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); @@ -143,14 +143,14 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * One match, but register update needed */ + @Test + @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { ArrayList zmrResult = new ArrayList<>(); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); @@ -163,17 +163,16 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * Two matches found in ZMR */ - public void testNode101_ManualFixNecessary_a() throws Exception { + @Test + @DirtiesContext + public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); @@ -182,22 +181,19 @@ public class InitialSearchTaskFirstTest { ArrayList ernpResult = new ArrayList<>(); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - try { - task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } - @Test - @DirtiesContext /** * Two matches found in ErnP */ - public void testNode101_ManualFixNecessary_b() throws Exception { + @Test + @DirtiesContext + public void testNode101_ManualFixNecessary_b() { String randombpk = RandomStringUtils.random(5); ArrayList zmrResult = new ArrayList<>(); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); @@ -209,20 +205,17 @@ public class InitialSearchTaskFirstTest { randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - try { - task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } - @Test - @DirtiesContext /** * One match, no register update needed */ + @Test + @DirtiesContext public void testNode102_UserIdentified_a() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(12); ArrayList zmrResult = new ArrayList<>(); @@ -235,14 +228,14 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * One match, no register update needed */ + @Test + @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(14); @@ -256,14 +249,14 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * One match found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode103_UserIdentified_IT() throws Exception { String bpkRegister = RandomStringUtils.randomNumeric(14); String taxNumber = RandomStringUtils.randomNumeric(14); @@ -291,22 +284,18 @@ public class InitialSearchTaskFirstTest { handlers.add(it); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); + task.execute(pendingReq1, executionContext); - String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(bpkRegister)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + String bPk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, bpkRegister); } - @Test - @DirtiesContext /** * Multiple matches found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode103_UserIdentified_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; @@ -339,22 +328,18 @@ public class InitialSearchTaskFirstTest { handlers.add(de); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); + task.execute(pendingReq1, executionContext); - String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(bpk)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + String bPk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, bpk); } - @Test - @DirtiesContext /** * Multiple matches found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode104_ManualFixNecessary_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; @@ -393,20 +378,20 @@ public class InitialSearchTaskFirstTest { try { task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + Assert.fail("Wrong workflow, should not reach this point/ get a bpk"); } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } } - @Test - @DirtiesContext /** * Multiple matches found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode104_ManualFixNecessary_IT() throws Exception { - String fakeTaxNumber = RandomStringUtils.randomNumeric(14);; + String fakeTaxNumber = RandomStringUtils.randomNumeric(14); final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) @@ -432,20 +417,18 @@ public class InitialSearchTaskFirstTest { handlers.add(it); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } - @Test - @DirtiesContext /** * NO match found in ZMR and ErnP with Initial search */ + @Test + @DirtiesContext public void testNode105_TemporaryEnd() throws TaskExecutionException { ArrayList zmrResult = new ArrayList<>(); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); @@ -509,17 +492,17 @@ public class InitialSearchTaskFirstTest { "afaf").attributes(attributeMap).build(); } - private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".LiteralStringAttributeValueMarshaller"); } - private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".DateTimeAttributeValueMarshaller"); } - private AttributeDefinition generateAttribute(String friendlyName, String fragment, String prefix, + private AttributeDefinition generateAttribute(String friendlyName, String fragment, String prefix, String marshaller) throws URISyntaxException { return AttributeDefinition.builder() .friendlyName(friendlyName).nameUri(new URI("ad", "sd", fragment)) -- cgit v1.2.3 From fb99ff15185b4f3b10d4c72270787b04281494bf Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:08:17 +0100 Subject: Use generic list types in parameters and return types List instead of ArrayList allows for easier mocking and stubbing --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 55 +++++++--------------- 1 file changed, 17 insertions(+), 38 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 35e2e56e..1f512354 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -67,6 +67,7 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Random; @@ -136,9 +137,7 @@ public class InitialSearchTaskFirstTest { String newFirstName = RandomStringUtils.randomAlphabetic(5); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) @@ -152,9 +151,7 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); @@ -177,9 +174,7 @@ public class InitialSearchTaskFirstTest { zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); @@ -195,9 +190,7 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode101_ManualFixNecessary_b() { String randombpk = RandomStringUtils.random(5); - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), @@ -218,8 +211,7 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode102_UserIdentified_a() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(12); - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); @@ -242,9 +234,7 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) @@ -265,8 +255,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpkRegister, IT_ST+randomIdentifier+RandomStringUtils.random(2), @@ -276,8 +265,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -310,8 +298,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, @@ -320,8 +307,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -356,8 +342,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, @@ -368,8 +353,7 @@ public class InitialSearchTaskFirstTest { null, null)); Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -397,8 +381,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, @@ -409,8 +392,7 @@ public class InitialSearchTaskFirstTest { fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -430,11 +412,8 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode105_TemporaryEnd() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) -- cgit v1.2.3 From 130df15476c455adb1a232fc555917ff69f0f09b Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:13:47 +0100 Subject: Use random values in tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 111 +++++++++------------ 1 file changed, 47 insertions(+), 64 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 1f512354..c18dabb9 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -87,10 +87,10 @@ public class InitialSearchTaskFirstTest { final ExecutionContext executionContext = new ExecutionContextImpl(); private TestRequestImpl pendingReq; private final String randomIdentifier = RandomStringUtils.randomNumeric(10); - private final String randomFamilyName = RandomStringUtils.randomNumeric(11); - private final String randomGivenName = RandomStringUtils.randomNumeric(12); - private final String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); - private final String randomBirthName = RandomStringUtils.randomNumeric(12); + private final String randomFamilyName = RandomStringUtils.randomAlphabetic(10); + private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); + private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); + private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); private final String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); private final String DE_ST = "de/st/"; private final String IT_ST = "it/st/"; @@ -154,7 +154,8 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); + String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); + ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); task.execute(pendingReq, executionContext); @@ -172,7 +173,8 @@ public class InitialSearchTaskFirstTest { public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); + String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -189,13 +191,12 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode101_ManualFixNecessary_b() { - String randombpk = RandomStringUtils.random(5); + String randombpk = RandomStringUtils.randomNumeric(5); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), - randomFamilyName, - randomDate)); + String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); TaskExecutionException exception = assertThrows(TaskExecutionException.class, @@ -258,10 +259,9 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpkRegister, IT_ST+randomIdentifier+RandomStringUtils.random(2), - randomGivenName, - randomFamilyName, - randomDate, null, null, taxNumber, null)); + String newRandomPseudonym = IT_ST + randomIdentifier + RandomStringUtils.randomNumeric(2); + zmrResultSpecific.add(new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, + randomDate, null, null, taxNumber, null)); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); @@ -285,15 +285,10 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode103_UserIdentified_DE() throws Exception { - String givenName = randomGivenName; - String familyName = randomFamilyName; - String pseudonym = DE_ST + RandomStringUtils.random(5); - String bpk = RandomStringUtils.random(5); - String dateOfBirth = randomDate; - String placeOfBirth = randomPlaceOfBirth; - String birthName = randomBirthName; - final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym, - dateOfBirth, placeOfBirth, birthName); + String randomPseudonym = DE_ST + RandomStringUtils.randomNumeric(5); + String randomBpk = RandomStringUtils.randomNumeric(5); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); @@ -301,11 +296,11 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, - birthName, - null, null)); + zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName,null, null)); - Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -316,9 +311,9 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq1, executionContext); - String bPk = (String) + String resultBpk = (String) pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", bPk, bpk); + Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); } /** @@ -327,17 +322,12 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode104_ManualFixNecessary_DE() throws Exception { - String givenName = randomGivenName; - String familyName = randomFamilyName; - String pseudonym1 = DE_ST + RandomStringUtils.random(5); - String pseudonym2 = pseudonym1 + RandomStringUtils.random(2); - String bpk1 = RandomStringUtils.random(5); - String bpk2 = bpk1 + RandomStringUtils.random(2); - String dateOfBirth = randomDate; - String placeOfBirth = randomPlaceOfBirth; - String birthName = randomBirthName; - final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym1, - dateOfBirth, placeOfBirth, birthName); + String pseudonym1 = DE_ST + RandomStringUtils.randomNumeric(5); + String pseudonym2 = pseudonym1 + RandomStringUtils.randomNumeric(2); + String bpk1 = RandomStringUtils.randomNumeric(5); + String bpk2 = bpk1 + RandomStringUtils.randomNumeric(2); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, pseudonym1, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); @@ -345,13 +335,12 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, - birthName, - null, null)); - zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, - birthName, - null, null)); - Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName,null, null)); + zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName,null, null)); + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -360,13 +349,10 @@ public class InitialSearchTaskFirstTest { handlers.add(de); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); - Assert.fail("Wrong workflow, should not reach this point/ get a bpk"); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } /** @@ -384,12 +370,10 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, - randomDate, null, null, - fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, randomFamilyName, - randomDate, null, null, - fakeTaxNumber, null)); + zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, + randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); + zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, + randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -424,13 +408,12 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, - DE_ST+randomIdentifier, randomDate); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST+randomIdentifier, randomDate); } private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, - IT_ST+randomIdentifier, randomDate, taxNumber, null, null); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST+randomIdentifier, randomDate, + taxNumber, null, null); } @NotNull -- cgit v1.2.3 From ccad318ae01794b246f5ca02c954fe94a92be515 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:25:51 +0100 Subject: Use clear Arrange-Act-Assert structure in tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 88 ++++++++-------------- 1 file changed, 31 insertions(+), 57 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index c18dabb9..99764aad 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -135,13 +135,15 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); String newFirstName = RandomStringUtils.randomAlphabetic(5); - zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); + String randomPseudonym = DE_ST + randomIdentifier; + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, randomPseudonym, newFirstName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -152,19 +154,18 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); - ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - /** * Two matches found in ZMR */ @@ -180,6 +181,7 @@ public class InitialSearchTaskFirstTest { TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -201,6 +203,7 @@ public class InitialSearchTaskFirstTest { TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -213,10 +216,8 @@ public class InitialSearchTaskFirstTest { public void testNode102_UserIdentified_a() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(12); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - ArrayList ernpResult = new ArrayList<>(); - ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) @@ -231,13 +232,12 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(14); - - ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); + String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); @@ -255,22 +255,14 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - String newRandomPseudonym = IT_ST + randomIdentifier + RandomStringUtils.randomNumeric(2); - zmrResultSpecific.add(new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, - randomDate, null, null, taxNumber, null)); - - Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); - + Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( + new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, + randomDate, null, null, taxNumber, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(it); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); + task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); @@ -292,22 +284,14 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - - zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName,null, null)); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)).thenReturn(zmrResultSpecific); - + randomBirthName)) + .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(de); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); + task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); @@ -331,26 +315,21 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null)); zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null)); Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(de); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); + task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -366,26 +345,20 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(it); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); - + task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -400,6 +373,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); + String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); -- cgit v1.2.3 From 2e8313758ae4d55274319200aba9226e65f2a82c Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:50:57 +0100 Subject: Rename variables in test for better readability --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 177 +++++++++++---------- 1 file changed, 94 insertions(+), 83 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 99764aad..9f58ba71 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -28,7 +28,6 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.RegisterResult; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.CountrySpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; @@ -68,7 +67,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; -import java.util.List; import java.util.Random; import static org.junit.Assert.assertThrows; @@ -78,6 +76,9 @@ import static org.junit.Assert.assertThrows; @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskFirstTest { + private static final String DE_ST = "de/st/"; + private static final String IT_ST = "it/st/"; + private InitialSearchTask task; @Mock private IZmrClient zmrClient; @@ -86,14 +87,14 @@ public class InitialSearchTaskFirstTest { final ExecutionContext executionContext = new ExecutionContextImpl(); private TestRequestImpl pendingReq; + private final String randomBpk = RandomStringUtils.randomNumeric(6); private final String randomIdentifier = RandomStringUtils.randomNumeric(10); + private final String randomPseudonym = DE_ST + randomIdentifier; private final String randomFamilyName = RandomStringUtils.randomAlphabetic(10); private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); - private final String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); - private final String DE_ST = "de/st/"; - private final String IT_ST = "it/st/"; + private final String randomDate = "2011-01-" + (10 + new Random().nextInt(18)); /** * jUnit class initializer. @@ -132,17 +133,15 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - ArrayList zmrResult = new ArrayList<>(); - String randomBpk = RandomStringUtils.randomNumeric(6); - String newFirstName = RandomStringUtils.randomAlphabetic(5); - String randomPseudonym = DE_ST + randomIdentifier; + String newFirstName = RandomStringUtils.randomAlphabetic(10); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomPseudonym, newFirstName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, newFirstName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -154,14 +153,14 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - String randomBpk = RandomStringUtils.randomNumeric(6); String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -173,14 +172,14 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); + () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -193,16 +192,16 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode101_ManualFixNecessary_b() { - String randombpk = RandomStringUtils.randomNumeric(5); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); - ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + ernpResult.add( + new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); + () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -214,14 +213,14 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode102_UserIdentified_a() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(12); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -231,15 +230,15 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(14); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -249,7 +248,6 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode103_UserIdentified_IT() throws Exception { - String bpkRegister = RandomStringUtils.randomNumeric(14); String taxNumber = RandomStringUtils.randomNumeric(14); final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); @@ -258,17 +256,19 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); String newRandomPseudonym = IT_ST + randomIdentifier + RandomStringUtils.randomNumeric(2); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( - new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, - randomDate, null, null, taxNumber, null))); + new RegisterResult(randomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, + randomDate, null, null, taxNumber, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", bPk, bpkRegister); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } /** @@ -277,26 +277,27 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode103_UserIdentified_DE() throws Exception { - String randomPseudonym = DE_ST + RandomStringUtils.randomNumeric(5); - String randomBpk = RandomStringUtils.randomNumeric(5); - final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, randomPseudonym, - randomDate, randomPlaceOfBirth, randomBirthName); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, + randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)) - .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, - randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null))); + randomBirthName)) + .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); String resultBpk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); } @@ -306,29 +307,30 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode104_ManualFixNecessary_DE() throws Exception { - String pseudonym1 = DE_ST + RandomStringUtils.randomNumeric(5); - String pseudonym2 = pseudonym1 + RandomStringUtils.randomNumeric(2); - String bpk1 = RandomStringUtils.randomNumeric(5); - String bpk2 = bpk1 + RandomStringUtils.randomNumeric(2); - final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, pseudonym1, - randomDate, randomPlaceOfBirth, randomBirthName); + String newRandomPseudonym = randomPseudonym + RandomStringUtils.randomNumeric(2); + String newRandomBpk = randomBpk + RandomStringUtils.randomNumeric(6); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, + randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName,null, null)); - zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName,null, null)); + zmrResultSpecific.add( + new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName, null, null)); + zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName, null, null)); Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)).thenReturn(zmrResultSpecific); + randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq1, executionContext)); + () -> task.execute(pendingReq1, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -340,24 +342,28 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode104_ManualFixNecessary_IT() throws Exception { - String fakeTaxNumber = RandomStringUtils.randomNumeric(14); - final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); + String randomTaxNumber = RandomStringUtils.randomNumeric(14); + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(randomTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, - randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, - randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); - Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); + String randomPseudonym = IT_ST + randomIdentifier + "4"; + zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + String newRandomPseudonym = IT_ST + randomIdentifier + "5"; + String newRandomBpk = RandomStringUtils.randomNumeric(6); + zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, + randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + Mockito.when(zmrClient.searchItSpecific(randomTaxNumber)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq1, executionContext)); + () -> task.execute(pendingReq1, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -375,19 +381,21 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); } @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST+randomIdentifier, randomDate); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomIdentifier, randomDate); } - private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST+randomIdentifier, randomDate, - taxNumber, null, null); + private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) + throws URISyntaxException { + return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST + randomIdentifier, randomDate, + taxNumber, null, null); } @NotNull @@ -408,18 +416,19 @@ public class InitialSearchTaskFirstTest { String dateOfBirth, String taxNumber, String placeOfBirth, String birthName) throws URISyntaxException { ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() - .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER,"ff","af"), identifier) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME,"fff","aff"), familyName) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME,"ffff","afff"), givenName) - .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH,"fffff","affff"), dateOfBirth); + .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER, "ff", "af"), identifier) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, "fff", "aff"), familyName) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME, "ffff", "afff"), givenName) + .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH, "fffff", "affff"), dateOfBirth); if (taxNumber != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE,"ffffff","afffff"), taxNumber); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE, "ffffff", "afffff"), taxNumber); } if (birthName != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME,"fffffff","affffff"), birthName); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME, "fffffff", "affffff"), birthName); } if (placeOfBirth != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH,"ffffffff","afffffff"), placeOfBirth); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH, "ffffffff", "afffffff"), + placeOfBirth); } final ImmutableAttributeMap attributeMap = builder.build(); @@ -428,18 +437,20 @@ public class InitialSearchTaskFirstTest { "afaf").attributes(attributeMap).build(); } - private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) + throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".LiteralStringAttributeValueMarshaller"); } - private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) + throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".DateTimeAttributeValueMarshaller"); } private AttributeDefinition generateAttribute(String friendlyName, String fragment, String prefix, - String marshaller) throws URISyntaxException { + 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)) -- cgit v1.2.3 From 7e768d77fba98d75944367aa83aea13009ad0910 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Thu, 3 Dec 2020 10:13:44 +0100 Subject: general workflow steps 1-8 --- .../eidas/v2/test/validation/EidasRequestPreProcessingSecondTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 c44e803b..23175a18 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 @@ -100,7 +100,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()); -- cgit v1.2.3 From b02cb48667a1ffc95b7e104c3f287bfa1a384123 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Wed, 9 Dec 2020 08:53:28 +0100 Subject: added (non working) test --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 160 +++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java new file mode 100644 index 00000000..30f88ec8 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -0,0 +1,160 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import 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.protocol.impl.AuthenticationResponse; +import lombok.val; +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.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.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; + +@RunWith(SpringJUnit4ClassRunner.class) +//@RunWith(PowerMockRunner.class) +//@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/SpringTest-context_tasks_test.xml") +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) +//@RunWith(PowerMockRunner.class) +//@PrepareForTest(InitialSearchTaskFirstTest.class) +public class InitialSearchTaskFirstTest { + + @Autowired(required = true) + @Mock + private InitialSearchTask task; + + @Autowired(required = true) + private IConfiguration basicConfig; + + final ExecutionContext executionContext = new ExecutionContextImpl(); + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private TestRequestImpl pendingReq; + private DummySpConfiguration oaParam; + + /** + * jUnit class initializer. + * + * @throws IOException In case of an error + */ + @BeforeClass + public static void classInitializer() throws IOException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/junit_config_1.properties"); + + } + + /** + * jUnit test set-up. + * + */ + @Before + public void setUp() throws URISyntaxException, EaafStorageException { + + task = PowerMockito.spy(task); + + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + final AuthenticationResponse response = buildDummyAuthResponse(); + pendingReq = new TestRequestImpl(); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + + } + + @Test + @DirtiesContext + public void testInitialSearch() throws Exception { + + try { + task.execute(pendingReq, executionContext); + + } catch (final TaskExecutionException e) { + // forward URL is not set in example config + // org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e.getOriginalException(), + // "Wrong exception"); + // Assert.assertEquals("wrong errorCode", "config.08", ((EaafException) e.getOriginalException()) + // .getErrorId()); + // Assert.assertEquals("wrong parameter size", 1, ((EaafException) e.getOriginalException()) + // .getParams().length); + // Assert.assertEquals("wrong errorMsg", Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL, ((EaafException) e + // .getOriginalException()).getParams()[0]); + + } +// verifyPrivate(task, times(1)).invoke("step2", ArgumentMatchers.any(SimpleEidasData.class)); +// verifyPrivate(task, times(0)).invoke("step3", ArgumentMatchers.any()); +// verifyPrivate(task, times(0)).invoke("step4", ArgumentMatchers.any()); + + } + + + @NotNull + private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { + final AttributeDefinition attributeDef = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef2 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME).nameUri(new URI("ad", "sd", "fff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "aff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef3 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME).nameUri(new URI("ad", "sd", "ffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef4 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH).nameUri(new URI("ad", "sd", "fffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); + + final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder() + .put(attributeDef, "de/st/" + RandomStringUtils.randomNumeric(64)) + .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) + .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)).put(attributeDef4, "2001-01-01").build(); + + val b = new AuthenticationResponse.Builder(); + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf") + .attributes(attributeMap).build(); + } +} -- cgit v1.2.3 From 710cae803e5b6846e1ec2a584bf9be1b57c8d23a Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 11 Dec 2020 17:16:50 +0100 Subject: added two tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 135 +++++++++++++++------ 1 file changed, 96 insertions(+), 39 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 30f88ec8..1b1bdeae 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -1,10 +1,13 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.RegisterResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.DummyErnbClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.DummyZmrClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; 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; @@ -23,12 +26,10 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -38,30 +39,29 @@ 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 org.junit.Assert; import javax.xml.namespace.QName; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; - -import static org.mockito.Mockito.times; -import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import java.util.ArrayList; @RunWith(SpringJUnit4ClassRunner.class) -//@RunWith(PowerMockRunner.class) -//@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) + @ContextConfiguration("/SpringTest-context_tasks_test.xml") @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) -//@RunWith(PowerMockRunner.class) -//@PrepareForTest(InitialSearchTaskFirstTest.class) public class InitialSearchTaskFirstTest { @Autowired(required = true) @Mock + @InjectMocks private InitialSearchTask task; - @Autowired(required = true) - private IConfiguration basicConfig; + @Mock + private IZmrClient zmrClient; + + @Mock + private IErnbClient ernbClient; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -71,7 +71,7 @@ public class InitialSearchTaskFirstTest { /** * jUnit class initializer. - * + * * @throws IOException In case of an error */ @BeforeClass @@ -84,7 +84,6 @@ public class InitialSearchTaskFirstTest { /** * jUnit test set-up. - * */ @Before public void setUp() throws URISyntaxException, EaafStorageException { @@ -96,41 +95,97 @@ public class InitialSearchTaskFirstTest { RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - final AuthenticationResponse response = buildDummyAuthResponse(); + final AuthenticationResponse response = buildDummyAuthResponseMaxMustermann(); pendingReq = new TestRequestImpl(); pendingReq.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); } - + @Test @DirtiesContext - public void testInitialSearch() throws Exception { + /** + * Two matches found in ZMR + */ + public void testNode101a() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); try { task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); } catch (final TaskExecutionException e) { - // forward URL is not set in example config - // org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e.getOriginalException(), - // "Wrong exception"); - // Assert.assertEquals("wrong errorCode", "config.08", ((EaafException) e.getOriginalException()) - // .getErrorId()); - // Assert.assertEquals("wrong parameter size", 1, ((EaafException) e.getOriginalException()) - // .getParams().length); - // Assert.assertEquals("wrong errorMsg", Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL, ((EaafException) e - // .getOriginalException()).getParams()[0]); - + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } -// verifyPrivate(task, times(1)).invoke("step2", ArgumentMatchers.any(SimpleEidasData.class)); -// verifyPrivate(task, times(0)).invoke("step3", ArgumentMatchers.any()); -// verifyPrivate(task, times(0)).invoke("step4", ArgumentMatchers.any()); + } + + + @Test + @DirtiesContext + /** + * Two matches found in ErnB + */ + public void testNode101b() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + } catch (final TaskExecutionException e) { + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } } @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { + return buildDummyAuthResponse(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + "de/st/" + RandomStringUtils.randomNumeric(64), "2001-01-01"); + } + + @NotNull + private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { + return buildDummyAuthResponse("Max", "Mustermann", + "de/st/max123", "1111-01-01"); + } + + @NotNull + private AuthenticationResponse buildDummyAuthResponse(String givenName, String familyName, String identifier, + String dateOfBirth) throws URISyntaxException { final AttributeDefinition attributeDef = AttributeDefinition.builder() .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) @@ -149,12 +204,14 @@ public class InitialSearchTaskFirstTest { .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder() - .put(attributeDef, "de/st/" + RandomStringUtils.randomNumeric(64)) - .put(attributeDef2, RandomStringUtils.randomAlphabetic(10)) - .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)).put(attributeDef4, "2001-01-01").build(); + .put(attributeDef, identifier) + .put(attributeDef2, familyName) + .put(attributeDef3, givenName) + .put(attributeDef4, dateOfBirth).build(); val b = new AuthenticationResponse.Builder(); - return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat("afaf") + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( + "afaf") .attributes(attributeMap).build(); } } -- cgit v1.2.3 From 41a2c873d585d00ee06cc95a5e30fe17f4bc85a9 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Tue, 15 Dec 2020 23:07:53 +0100 Subject: added machting (3-4) + tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 140 ++++++++++++++++++++- 1 file changed, 136 insertions(+), 4 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 1b1bdeae..2614f9ba 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -111,8 +111,8 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); - zmrResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); @@ -151,8 +151,8 @@ public class InitialSearchTaskFirstTest { //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("de/st/max123", "Max", "Mustermann", "1111-01-01")); - ernbResult.add(new RegisterResult("de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -170,6 +170,138 @@ public class InitialSearchTaskFirstTest { } } + @Test + @DirtiesContext + /** + * One match, but register update needed + */ + public void testNode100a() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + String randomBpk = RandomStringUtils.randomNumeric(6); + zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); + + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * One match, but register update needed + */ + public void testNode100b() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + String randomBpk = RandomStringUtils.randomNumeric(6); + ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * One match, no register update needed + */ + public void testNode102a() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * One match, no register update needed + */ + public void testNode102b() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { -- cgit v1.2.3 From ad3f9df147e671522ebbae47e667ce06ef52bf9c Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Tue, 15 Dec 2020 23:57:14 +0100 Subject: Testcase no match found added --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 2614f9ba..924a180d 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -303,6 +303,38 @@ public class InitialSearchTaskFirstTest { } } + + @Test + @DirtiesContext + /** + * NO match found in ZMR and ErnB with Initial search + */ + public void testNode105() throws Exception { + + //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? + task.setZmrClient(zmrClient); + + //Mock ernb + ArrayList ernbResult = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("105")); + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { return buildDummyAuthResponse(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), -- cgit v1.2.3 From 20b28fa85e5fc24868b22fa769e87f1dcacf205a Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Wed, 16 Dec 2020 17:32:43 +0100 Subject: 2 more tests (bean mocking still missing) --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 85 +++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 924a180d..5c75d1e4 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -22,8 +22,10 @@ import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; import lombok.val; import org.apache.commons.lang3.RandomStringUtils; import org.jetbrains.annotations.NotNull; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -39,7 +41,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import org.junit.Assert; + import javax.xml.namespace.QName; import java.io.IOException; import java.net.URI; @@ -303,6 +305,87 @@ public class InitialSearchTaskFirstTest { } } + @Ignore + @Test + @DirtiesContext + /** + * One match found in ZMR and ErnB with detail search + */ + public void testNode103() throws Exception { + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, + // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address + zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, + "tax123", null)); + + Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Ignore + @Test + @DirtiesContext + /** + * Multiple matches found in ZMR and ErnB with detail search + */ + public void testNode104() throws Exception { + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, + // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address + zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, + "tax123", null)); + zmrResultSpecific.add(new RegisterResult("bpkMax1","de/st/max1235", "Max", "Mustermann", "1111-01-01", null, null, + "tax123", null)); + Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + + + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + try { + task.execute(pendingReq, executionContext); + + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + + } catch (final TaskExecutionException e) { + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + } + @Test @DirtiesContext -- cgit v1.2.3 From 21613f2d1af10639b65077c5600763e82b5eb63c Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Thu, 17 Dec 2020 13:18:37 +0100 Subject: country specific tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 305 +++++++++++++++++---- 1 file changed, 251 insertions(+), 54 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 5c75d1e4..64a73bda 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -5,6 +5,9 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.RegisterResult; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.DummyErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ICountrySpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.DummyZmrClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; @@ -25,7 +28,6 @@ import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -47,6 +49,7 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; +import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @@ -107,54 +110,55 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Two matches found in ZMR + * One match, but register update needed */ - public void testNode101a() throws Exception { + public void testNode100a() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + String randomBpk = RandomStringUtils.randomNumeric(6); + zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? task.setErnbClient(ernbClient); try { task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong workflow, should not reach this point", false); } } - @Test @DirtiesContext /** - * Two matches found in ErnB + * One match, but register update needed */ - public void testNode101b() throws Exception { + public void testNode100b() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "1111-01-01")); + String randomBpk = RandomStringUtils.randomNumeric(6); + ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -162,68 +166,67 @@ public class InitialSearchTaskFirstTest { try { task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong workflow, should not reach this point", false); } } + @Test @DirtiesContext /** - * One match, but register update needed + * Two matches found in ZMR */ - public void testNode100a() throws Exception { + public void testNode101a() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - String randomBpk = RandomStringUtils.randomNumeric(6); - zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); - + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? task.setErnbClient(ernbClient); try { task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } } + @Test @DirtiesContext /** - * One match, but register update needed + * Two matches found in ErnB */ - public void testNode100b() throws Exception { + public void testNode101b() throws Exception { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - String randomBpk = RandomStringUtils.randomNumeric(6); - ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -231,12 +234,13 @@ public class InitialSearchTaskFirstTest { try { task.execute(pendingReq, executionContext); + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } } @@ -255,7 +259,7 @@ public class InitialSearchTaskFirstTest { //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); ernbClient = Mockito.mock(DummyErnbClient.class); Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? @@ -281,7 +285,7 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "1111-01-01")); + zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? @@ -305,13 +309,18 @@ public class InitialSearchTaskFirstTest { } } - @Ignore @Test @DirtiesContext /** * One match found in ZMR and ErnB with detail search */ - public void testNode103() throws Exception { + public void testNode103IT() throws Exception { + String bpkRegister = "bpkMax"; + String taxNumber = "tax123"; + final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(taxNumber); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); @@ -320,10 +329,10 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResultSpecific = new ArrayList<>(); //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, - "tax123", null)); + zmrResultSpecific.add(new RegisterResult(bpkRegister,"it/st/max1234", "Max", "Mustermann", "2011-01-01", null, + null, taxNumber, null)); - Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); task.setZmrClient(zmrClient); //Mock ernb initial search @@ -333,24 +342,160 @@ public class InitialSearchTaskFirstTest { task.setErnbClient(ernbClient); + //Mock country specific search + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); + it.setErnbClient(ernbClient); + it.setZmrClient(zmrClient); + handlers.add(it); + task.setHandlers(handlers); + try { - task.execute(pendingReq, executionContext); + task.execute(pendingReq1, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(bpkRegister)); + } catch (final TaskExecutionException e) { + Assert.assertTrue("Wrong workflow, should not reach this point", false); + } + } + + @Test + @DirtiesContext + /** + * Multiple matches found in ZMR and ErnB with detail search + */ + public void testNode103DE() throws Exception { + String givenName = "Max"; + String familyName = "Mustermann"; + String pseudonym = "de/st/max1234"; + String bpk = "bpkMax"; + String dateOfBirth = "2011-01-01"; + String placeOfBirth = "München"; + String birthName = "BabyMax"; + final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym, + dateOfBirth, placeOfBirth, birthName); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + + zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + null, null)); + + //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), + // eidData.getPlaceOfBirth(), eidData.getBirthName() + Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + //Mock country specific search + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); + de.setErnbClient(ernbClient); + de.setZmrClient(zmrClient); + handlers.add(de); + task.setHandlers(handlers); + + try { + task.execute(pendingReq1, executionContext); + + String bPk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(bpk)); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); } } - @Ignore @Test @DirtiesContext /** * Multiple matches found in ZMR and ErnB with detail search */ - public void testNode104() throws Exception { + public void testNode104DE() throws Exception { + String givenName = "Max"; + String familyName = "Mustermann"; + String pseudonym1 = "de/st/max1234"; + String pseudonym2 = "de/st/max12345"; + String bpk1 = "bpkMax"; + String bpk2 = "bpkMax1"; + String dateOfBirth = "2011-01-01"; + String placeOfBirth = "München"; + String birthName = "BabyMax"; + final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym1, + dateOfBirth, placeOfBirth, birthName); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + + //Mock ZMR initial search + ArrayList zmrResultInitial = new ArrayList<>(); + zmrClient = Mockito.mock(DummyZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + ArrayList zmrResultSpecific = new ArrayList<>(); + + zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + null, null)); + zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + null, null)); + //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), + // eidData.getPlaceOfBirth(), eidData.getBirthName() + Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + + task.setZmrClient(zmrClient); + + //Mock ernb initial search + ArrayList ernbResultInitial = new ArrayList<>(); + ernbClient = Mockito.mock(DummyErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + + task.setErnbClient(ernbClient); + + //Mock country specific search + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); + de.setErnbClient(ernbClient); + de.setZmrClient(zmrClient); + handlers.add(de); + task.setHandlers(handlers); + + try { + task.execute(pendingReq1, executionContext); + + Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + + } catch (final TaskExecutionException e) { + Throwable origE = e.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + } + + @Test + @DirtiesContext + /** + * Multiple matches found in ZMR and ErnB with detail search + */ + public void testNode104IT() throws Exception { + + String fakeTaxNumber = "tax123"; + final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(fakeTaxNumber); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); @@ -359,11 +504,11 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResultSpecific = new ArrayList<>(); //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult("bpkMax","de/st/max1234", "Max", "Mustermann", "1111-01-01", null, null, - "tax123", null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1","de/st/max1235", "Max", "Mustermann", "1111-01-01", null, null, - "tax123", null)); - Mockito.when(zmrClient.searchItSpecific("tax123")).thenReturn(zmrResultSpecific); + zmrResultSpecific.add(new RegisterResult("bpkMax","it/st/max1234", "Max", "Mustermann", "2011-01-01", null, null, + fakeTaxNumber, null)); + zmrResultSpecific.add(new RegisterResult("bpkMax1","it/st/max1235", "Max", "Mustermann", "2011-01-01", null, null, + fakeTaxNumber, null)); + Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); task.setZmrClient(zmrClient); @@ -375,8 +520,16 @@ public class InitialSearchTaskFirstTest { task.setErnbClient(ernbClient); + //Mock country specific search + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); + it.setErnbClient(ernbClient); + it.setZmrClient(zmrClient); + handlers.add(it); + task.setHandlers(handlers); + try { - task.execute(pendingReq, executionContext); + task.execute(pendingReq1, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -386,7 +539,6 @@ public class InitialSearchTaskFirstTest { } } - @Test @DirtiesContext /** @@ -427,12 +579,35 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { return buildDummyAuthResponse("Max", "Mustermann", - "de/st/max123", "1111-01-01"); + "de/st/max123", "2011-01-01"); + } + + private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT() throws URISyntaxException { + return buildDummyAuthResponse("Max", "Mustermann", + "it/st/max123", "2011-01-01"); + } + + private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT_Tax(String taxNumber) throws URISyntaxException { + return buildDummyAuthResponse("Max", "Mustermann", + "it/st/max123", "2011-01-01", taxNumber, null, null); } @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 { final AttributeDefinition attributeDef = AttributeDefinition.builder() .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) @@ -449,12 +624,34 @@ public class InitialSearchTaskFirstTest { .friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH).nameUri(new URI("ad", "sd", "fffff")) .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affff")) .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); - - final ImmutableAttributeMap attributeMap = ImmutableAttributeMap.builder() + final AttributeDefinition attributeDef5 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_TAXREFERENCE).nameUri(new URI("ad", "sd", "ffffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef6 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_PLACEOFBIRTH).nameUri(new URI("ad", "sd", "fffffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affffff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + final AttributeDefinition attributeDef7 = AttributeDefinition.builder() + .friendlyName(Constants.eIDAS_ATTR_BIRTHNAME).nameUri(new URI("ad", "sd", "ffffffff")) + .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffffff")) + .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); + ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() .put(attributeDef, identifier) .put(attributeDef2, familyName) .put(attributeDef3, givenName) - .put(attributeDef4, dateOfBirth).build(); + .put(attributeDef4, dateOfBirth); + + if(taxNumber != null) { + builder.put(attributeDef5, taxNumber); + } + if(birthName != null) { + builder.put(attributeDef7, birthName); + } + if(placeOfBirth != null) { + builder.put(attributeDef6, placeOfBirth); + } + final ImmutableAttributeMap attributeMap = builder.build(); val b = new AuthenticationResponse.Builder(); return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( -- cgit v1.2.3 From 1dd2f63eb54befa7b347051c509d33dd8448bff0 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Fri, 18 Dec 2020 10:22:59 +0100 Subject: Review code --- .../eidas/v2/test/tasks/InitialSearchTaskFirstTest.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 64a73bda..d366fefc 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -62,9 +62,11 @@ public class InitialSearchTaskFirstTest { @InjectMocks private InitialSearchTask task; + // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? @Mock private IZmrClient zmrClient; + // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? @Mock private IErnbClient ernbClient; @@ -92,7 +94,7 @@ public class InitialSearchTaskFirstTest { */ @Before public void setUp() throws URISyntaxException, EaafStorageException { - + // NOTE: PowerMockito should not be needed, as we don't want to test static and private methods task = PowerMockito.spy(task); httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); @@ -112,6 +114,7 @@ public class InitialSearchTaskFirstTest { /** * One match, but register update needed */ + // NOTE: Why is the method named "testNode100a"? public void testNode100a() throws Exception { //Mock ZMR @@ -119,6 +122,9 @@ public class InitialSearchTaskFirstTest { String randomBpk = RandomStringUtils.randomNumeric(6); zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + // NOTE: Are we using Mockito or these fixed strings in DummyZmrClient? + // NOTE: Please mock an interface, not a concrete class + // NOTE: But DummyZmrClient is also defined as a bean "ZmrClientForeIDAS" in "eidas_v2_auth.beans.xml"? zmrClient = Mockito.mock(DummyZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? task.setZmrClient(zmrClient); @@ -137,11 +143,13 @@ public class InitialSearchTaskFirstTest { Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { + // NOTE: assertTrue is probably the wrong method to use ... why catch the exception anyway? Assert.assertTrue("Wrong workflow, should not reach this point", false); } } @Test + // NOTE: Why is @DirtiesContext after each test necessary? What is changed in the context and why? @DirtiesContext /** * One match, but register update needed @@ -563,6 +571,7 @@ public class InitialSearchTaskFirstTest { String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + // NOTE: Why "105"? Extract in a constant Assert.assertTrue("Wrong bpk", bPk.equals("105")); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); @@ -578,6 +587,8 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { + // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string again? + // NOTE: If not, why not using random strings? return buildDummyAuthResponse("Max", "Mustermann", "de/st/max123", "2011-01-01"); } -- cgit v1.2.3 From 65da83cd168a87fe15c6e03a0178fe78780854fd Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 18 Dec 2020 17:24:55 +0100 Subject: constructor based injection, randomized values for testing, added constants --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 289 ++++++++------------- 1 file changed, 115 insertions(+), 174 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index d366fefc..f7fc6b06 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -2,20 +2,17 @@ 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.RegisterResult; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.DummyErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ICountrySpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.DummyZmrClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; import eu.eidas.auth.commons.attribute.AttributeDefinition; @@ -33,7 +30,6 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -62,20 +58,16 @@ public class InitialSearchTaskFirstTest { @InjectMocks private InitialSearchTask task; - // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? - @Mock private IZmrClient zmrClient; - - // NOTE: Is defined as @Mock, but also manually mocked in "testNode100a" etc -- why? - @Mock private IErnbClient ernbClient; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; private MockHttpServletResponse httpResp; private TestRequestImpl pendingReq; - private DummySpConfiguration oaParam; - + private String randomIdentifier = RandomStringUtils.randomNumeric(10); + private String randomFamilyName = RandomStringUtils.randomNumeric(11); + private String randomGivenName = RandomStringUtils.randomNumeric(12); /** * jUnit class initializer. * @@ -86,7 +78,6 @@ public class InitialSearchTaskFirstTest { final String current = new java.io.File(".").toURI().toString(); System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_1.properties"); - } /** @@ -94,19 +85,15 @@ public class InitialSearchTaskFirstTest { */ @Before public void setUp() throws URISyntaxException, EaafStorageException { - // NOTE: PowerMockito should not be needed, as we don't want to test static and private methods - task = PowerMockito.spy(task); - httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - final AuthenticationResponse response = buildDummyAuthResponseMaxMustermann(); + final AuthenticationResponse response = buildDummyAuthResponseRandomPerson(); pendingReq = new TestRequestImpl(); pendingReq.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - } @Test @@ -120,22 +107,18 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - zmrResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); - // NOTE: Are we using Mockito or these fixed strings in DummyZmrClient? - // NOTE: Please mock an interface, not a concrete class - // NOTE: But DummyZmrClient is also defined as a bean "ZmrClientForeIDAS" in "eidas_v2_auth.beans.xml"? - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) @@ -159,19 +142,18 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult);//"de/st/max123"??? //Mock ernb ArrayList ernbResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - ernbResult.add(new RegisterResult(randomBpk,"de/st/max123", "Max_new", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) @@ -193,24 +175,20 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -227,25 +205,21 @@ public class InitialSearchTaskFirstTest { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Maximilian", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -259,26 +233,25 @@ public class InitialSearchTaskFirstTest { */ public void testNode102a() throws Exception { + String randomBpk = RandomStringUtils.randomNumeric(12);; //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); - + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); } @@ -290,27 +263,26 @@ public class InitialSearchTaskFirstTest { * One match, no register update needed */ public void testNode102b() throws Exception { - + String randomBpk = RandomStringUtils.randomNumeric(14); //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax","de/st/max123", "Max", "Mustermann", "2011-01-01")); + zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("bpkMax")); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); @@ -323,40 +295,36 @@ public class InitialSearchTaskFirstTest { * One match found in ZMR and ErnB with detail search */ public void testNode103IT() throws Exception { - String bpkRegister = "bpkMax"; - String taxNumber = "tax123"; - final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(taxNumber); + String bpkRegister = RandomStringUtils.randomNumeric(14); + String taxNumber = RandomStringUtils.randomNumeric(14); + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult(bpkRegister,"it/st/max1234", "Max", "Mustermann", "2011-01-01", null, - null, taxNumber, null)); + zmrResultSpecific.add(new RegisterResult(bpkRegister, "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, + "2011-01-01", null, null, taxNumber, null)); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); - task.setZmrClient(zmrClient); //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); - task.setErnbClient(ernbClient); //Mock country specific search List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); - it.setErnbClient(ernbClient); - it.setZmrClient(zmrClient); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(it); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -375,8 +343,8 @@ public class InitialSearchTaskFirstTest { * Multiple matches found in ZMR and ErnB with detail search */ public void testNode103DE() throws Exception { - String givenName = "Max"; - String familyName = "Mustermann"; + String givenName = randomGivenName; + String familyName = randomFamilyName; String pseudonym = "de/st/max1234"; String bpk = "bpkMax"; String dateOfBirth = "2011-01-01"; @@ -390,33 +358,26 @@ public class InitialSearchTaskFirstTest { //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, + birthName, null, null)); - //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), - // eidData.getPlaceOfBirth(), eidData.getBirthName() Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - task.setZmrClient(zmrClient); - //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? - - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); //Mock country specific search List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); - de.setErnbClient(ernbClient); - de.setZmrClient(zmrClient); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(de); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -435,8 +396,8 @@ public class InitialSearchTaskFirstTest { * Multiple matches found in ZMR and ErnB with detail search */ public void testNode104DE() throws Exception { - String givenName = "Max"; - String familyName = "Mustermann"; + String givenName = randomGivenName; + String familyName = randomFamilyName; String pseudonym1 = "de/st/max1234"; String pseudonym2 = "de/st/max12345"; String bpk1 = "bpkMax"; @@ -452,34 +413,29 @@ public class InitialSearchTaskFirstTest { //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, + birthName, null, null)); - zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, birthName, + zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, + birthName, null, null)); - //.searchDeSpecific(eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth(), - // eidData.getPlaceOfBirth(), eidData.getBirthName() Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - task.setZmrClient(zmrClient); //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? - - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); //Mock country specific search List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(); - de.setErnbClient(ernbClient); - de.setZmrClient(zmrClient); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(de); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -498,43 +454,34 @@ public class InitialSearchTaskFirstTest { * Multiple matches found in ZMR and ErnB with detail search */ public void testNode104IT() throws Exception { - - String fakeTaxNumber = "tax123"; - final AuthenticationResponse response = buildDummyAuthResponseMaxMustermannIT_Tax(fakeTaxNumber); + String fakeTaxNumber = RandomStringUtils.randomNumeric(14);; + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResultInitial); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, - // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult("bpkMax","it/st/max1234", "Max", "Mustermann", "2011-01-01", null, null, + + zmrResultSpecific.add(new RegisterResult("bpkMax", "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, "2011-01-01", null, null, fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1","it/st/max1235", "Max", "Mustermann", "2011-01-01", null, null, + zmrResultSpecific.add(new RegisterResult("bpkMax1", "it/st/"+randomIdentifier+"5", randomGivenName, randomFamilyName, "2011-01-01", null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - - task.setZmrClient(zmrClient); - //Mock ernb initial search ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResultInitial);//"de/st/max123"??? - - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); //Mock country specific search List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(); - it.setErnbClient(ernbClient); - it.setZmrClient(zmrClient); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); handlers.add(it); - task.setHandlers(handlers); + task = new InitialSearchTask(handlers, ernbClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -552,27 +499,25 @@ public class InitialSearchTaskFirstTest { /** * NO match found in ZMR and ErnB with Initial search */ - public void testNode105() throws Exception { + public void testNode105() { //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(DummyZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer("max123")).thenReturn(zmrResult);//"de/st/max123"??? - task.setZmrClient(zmrClient); + zmrClient = Mockito.mock(IZmrClient.class); + Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); //Mock ernb ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(DummyErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer("max123")).thenReturn(ernbResult);//"de/st/max123"??? - task.setErnbClient(ernbClient); + ernbClient = Mockito.mock(IErnbClient.class); + Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); try { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - // NOTE: Why "105"? Extract in a constant - Assert.assertTrue("Wrong bpk", bPk.equals("105")); + Assert.assertTrue("Wrong bpk", bPk.equals("TODO-Temporary-Endnode-105")); } catch (final TaskExecutionException e) { Assert.assertTrue("Wrong workflow, should not reach this point", false); } @@ -580,27 +525,17 @@ public class InitialSearchTaskFirstTest { @NotNull - private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { - return buildDummyAuthResponse(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - "de/st/" + RandomStringUtils.randomNumeric(64), "2001-01-01"); - } - - @NotNull - private AuthenticationResponse buildDummyAuthResponseMaxMustermann() throws URISyntaxException { - // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string again? + private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { + // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string + // again? // NOTE: If not, why not using random strings? - return buildDummyAuthResponse("Max", "Mustermann", - "de/st/max123", "2011-01-01"); - } - - private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT() throws URISyntaxException { - return buildDummyAuthResponse("Max", "Mustermann", - "it/st/max123", "2011-01-01"); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, + "de/st/"+randomIdentifier, "2011-01-01"); } - private AuthenticationResponse buildDummyAuthResponseMaxMustermannIT_Tax(String taxNumber) throws URISyntaxException { - return buildDummyAuthResponse("Max", "Mustermann", - "it/st/max123", "2011-01-01", taxNumber, null, null); + private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { + return buildDummyAuthResponse(randomGivenName, randomFamilyName, + "it/st/"+randomIdentifier, "2011-01-01", taxNumber, null, null); } @NotNull @@ -611,10 +546,11 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseDE(String givenName, String familyName, String identifier, - String dateOfBirth, String placeOfBirth, + 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, @@ -653,13 +589,13 @@ public class InitialSearchTaskFirstTest { .put(attributeDef3, givenName) .put(attributeDef4, dateOfBirth); - if(taxNumber != null) { + if (taxNumber != null) { builder.put(attributeDef5, taxNumber); } - if(birthName != null) { + if (birthName != null) { builder.put(attributeDef7, birthName); } - if(placeOfBirth != null) { + if (placeOfBirth != null) { builder.put(attributeDef6, placeOfBirth); } final ImmutableAttributeMap attributeMap = builder.build(); @@ -669,4 +605,9 @@ public class InitialSearchTaskFirstTest { "afaf") .attributes(attributeMap).build(); } + + private List emptyHandlers() { + return new ArrayList<>(); + } + } -- cgit v1.2.3 From ed033b4105eec8c00189729bd4b38b17c6b40509 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Thu, 7 Jan 2021 18:16:45 +0100 Subject: Resolve merge comments --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 438 +++++++++------------ 1 file changed, 197 insertions(+), 241 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index f7fc6b06..a1dce0f2 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -1,11 +1,34 @@ +/* + * 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.dao.RegisterResult; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernb.IErnbClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ICountrySpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.CountrySpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; @@ -27,10 +50,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.Mockito; -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; @@ -46,6 +66,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; +import java.util.Random; @RunWith(SpringJUnit4ClassRunner.class) @@ -53,13 +74,9 @@ import java.util.List; @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskFirstTest { - @Autowired(required = true) - @Mock - @InjectMocks private InitialSearchTask task; - private IZmrClient zmrClient; - private IErnbClient ernbClient; + private IErnpClient ernpClient; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -68,6 +85,12 @@ public class InitialSearchTaskFirstTest { private String randomIdentifier = RandomStringUtils.randomNumeric(10); private String randomFamilyName = RandomStringUtils.randomNumeric(11); private String randomGivenName = RandomStringUtils.randomNumeric(12); + private String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); + private String randomBirthName = RandomStringUtils.randomNumeric(12); + private String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); + private String DE_ST = "de/st/"; + private String IT_ST = "it/st/"; + /** * jUnit class initializer. * @@ -101,68 +124,52 @@ public class InitialSearchTaskFirstTest { /** * One match, but register update needed */ - // NOTE: Why is the method named "testNode100a"? - public void testNode100a() throws Exception { + public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); + String newFirstName = RandomStringUtils.randomAlphabetic(5); + zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); - - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); - - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + ArrayList ernpResult = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - } catch (final TaskExecutionException e) { - // NOTE: assertTrue is probably the wrong method to use ... why catch the exception anyway? - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } @Test - // NOTE: Why is @DirtiesContext after each test necessary? What is changed in the context and why? @DirtiesContext /** * One match, but register update needed */ - public void testNode100b() throws Exception { + public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult);//"de/st/max123"??? + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); + ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, "Max_new", randomFamilyName, "2011-01-01")); + ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } } @@ -171,21 +178,19 @@ public class InitialSearchTaskFirstTest { /** * Two matches found in ZMR */ - public void testNode101a() throws Exception { + public void testNode101_ManualFixNecessary_a() throws Exception { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - zmrResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); + zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ArrayList ernpResult = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -199,24 +204,24 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Two matches found in ErnB + * Two matches found in ErnP */ - public void testNode101b() throws Exception { - - //Mock ZMR + public void testNode101_ManualFixNecessary_b() throws Exception { + String randombpk = RandomStringUtils.random(5); ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); - ernbResult.add(new RegisterResult("bpkMax", "de/st/"+randomIdentifier, "Maximilian", randomFamilyName, "2011-01-01")); + ArrayList ernpResult = new ArrayList<>(); + ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), + randomFamilyName, + randomDate)); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -231,30 +236,24 @@ public class InitialSearchTaskFirstTest { /** * One match, no register update needed */ - public void testNode102a() throws Exception { + public void testNode102_UserIdentified_a() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(12);; - //Mock ZMR + String randomBpk = RandomStringUtils.randomNumeric(12); ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + ArrayList ernpResult = new ArrayList<>(); + ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } @Test @@ -262,39 +261,33 @@ public class InitialSearchTaskFirstTest { /** * One match, no register update needed */ - public void testNode102b() throws Exception { + public void testNode102_UserIdentified_b() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(14); - //Mock ZMR + ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, "de/st/"+randomIdentifier, randomGivenName, randomFamilyName, "2011-01-01")); + zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); + ArrayList ernpResult = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); } @Test @DirtiesContext /** - * One match found in ZMR and ErnB with detail search + * One match found in ZMR and ErnP with detail search */ - public void testNode103IT() throws Exception { + public void testNode103_UserIdentified_IT() throws Exception { String bpkRegister = RandomStringUtils.randomNumeric(14); String taxNumber = RandomStringUtils.randomNumeric(14); final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); @@ -302,29 +295,26 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - //String bpk, String pseudonym, String givenName, String familyName, String dateOfBirth, - // String placeOfBirth, String birthName, String taxNumber, PostalAddressType address - zmrResultSpecific.add(new RegisterResult(bpkRegister, "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, - "2011-01-01", null, null, taxNumber, null)); - Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); + zmrResultSpecific.add(new RegisterResult(bpkRegister, IT_ST+randomIdentifier+RandomStringUtils.random(2), + randomGivenName, + randomFamilyName, + randomDate, null, null, taxNumber, null)); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); + Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock country specific search - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(it); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -340,26 +330,25 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Multiple matches found in ZMR and ErnB with detail search + * Multiple matches found in ZMR and ErnP with detail search */ - public void testNode103DE() throws Exception { + public void testNode103_UserIdentified_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; - String pseudonym = "de/st/max1234"; - String bpk = "bpkMax"; - String dateOfBirth = "2011-01-01"; - String placeOfBirth = "München"; - String birthName = "BabyMax"; + String pseudonym = DE_ST + RandomStringUtils.random(5); + String bpk = RandomStringUtils.random(5); + String dateOfBirth = randomDate; + String placeOfBirth = randomPlaceOfBirth; + String birthName = randomBirthName; final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym, dateOfBirth, placeOfBirth, birthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, @@ -368,16 +357,14 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock country specific search - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(de); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); @@ -393,28 +380,27 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Multiple matches found in ZMR and ErnB with detail search + * Multiple matches found in ZMR and ErnP with detail search */ - public void testNode104DE() throws Exception { + public void testNode104_ManualFixNecessary_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; - String pseudonym1 = "de/st/max1234"; - String pseudonym2 = "de/st/max12345"; - String bpk1 = "bpkMax"; - String bpk2 = "bpkMax1"; - String dateOfBirth = "2011-01-01"; - String placeOfBirth = "München"; - String birthName = "BabyMax"; + String pseudonym1 = DE_ST + RandomStringUtils.random(5); + String pseudonym2 = pseudonym1 + RandomStringUtils.random(2); + String bpk1 = RandomStringUtils.random(5); + String bpk2 = bpk1 + RandomStringUtils.random(2); + String dateOfBirth = randomDate; + String placeOfBirth = randomPlaceOfBirth; + String birthName = randomBirthName; final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym1, dateOfBirth, placeOfBirth, birthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, @@ -425,23 +411,18 @@ public class InitialSearchTaskFirstTest { null, null)); Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); - - //Mock country specific search - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(de); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -451,43 +432,40 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * Multiple matches found in ZMR and ErnB with detail search + * Multiple matches found in ZMR and ErnP with detail search */ - public void testNode104IT() throws Exception { + public void testNode104_ManualFixNecessary_IT() throws Exception { String fakeTaxNumber = RandomStringUtils.randomNumeric(14);; final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - //Mock ZMR initial search ArrayList zmrResultInitial = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", "it/st/"+randomIdentifier+"4", randomGivenName, randomFamilyName, "2011-01-01", null, null, + zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, + randomDate, null, null, fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1", "it/st/"+randomIdentifier+"5", randomGivenName, randomFamilyName, "2011-01-01", null, null, + zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, randomFamilyName, + randomDate, null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - //Mock ernb initial search - ArrayList ernbResultInitial = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResultInitial); + ArrayList ernpResultInitial = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); - //Mock country specific search - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernbClient, zmrClient); + List handlers = new ArrayList<>(); + ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); handlers.add(it); - task = new InitialSearchTask(handlers, ernbClient, zmrClient); + task = new InitialSearchTask(handlers, ernpClient, zmrClient); try { task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -497,45 +475,35 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext /** - * NO match found in ZMR and ErnB with Initial search + * NO match found in ZMR and ErnP with Initial search */ - public void testNode105() { + public void testNode105_TemporaryEnd() throws TaskExecutionException { - //Mock ZMR ArrayList zmrResult = new ArrayList<>(); zmrClient = Mockito.mock(IZmrClient.class); - Mockito.when(zmrClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(zmrResult); - - //Mock ernb - ArrayList ernbResult = new ArrayList<>(); - ernbClient = Mockito.mock(IErnbClient.class); - Mockito.when(ernbClient.searchWithPersonIdentifer(randomIdentifier)).thenReturn(ernbResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - task = new InitialSearchTask(emptyHandlers(), ernbClient, zmrClient); - try { - task.execute(pendingReq, executionContext); + ArrayList ernpResult = new ArrayList<>(); + ernpClient = Mockito.mock(IErnpClient.class); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals("TODO-Temporary-Endnode-105")); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); } @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - // NOTE: Those strings "de/st/max123" seem to be somehow relevant, but where do we need to use that exact string - // again? - // NOTE: If not, why not using random strings? return buildDummyAuthResponse(randomGivenName, randomFamilyName, - "de/st/"+randomIdentifier, "2011-01-01"); + DE_ST+randomIdentifier, randomDate); } private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { return buildDummyAuthResponse(randomGivenName, randomFamilyName, - "it/st/"+randomIdentifier, "2011-01-01", taxNumber, null, null); + IT_ST+randomIdentifier, randomDate, taxNumber, null, null); } @NotNull @@ -555,58 +523,46 @@ public class InitialSearchTaskFirstTest { private AuthenticationResponse buildDummyAuthResponse(String givenName, String familyName, String identifier, String dateOfBirth, String taxNumber, String placeOfBirth, String birthName) throws URISyntaxException { - final AttributeDefinition attributeDef = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).nameUri(new URI("ad", "sd", "ff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "af")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef2 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTFAMILYNAME).nameUri(new URI("ad", "sd", "fff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "aff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef3 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_CURRENTGIVENNAME).nameUri(new URI("ad", "sd", "ffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef4 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_DATEOFBIRTH).nameUri(new URI("ad", "sd", "fffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.DateTimeAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef5 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_TAXREFERENCE).nameUri(new URI("ad", "sd", "ffffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef6 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_PLACEOFBIRTH).nameUri(new URI("ad", "sd", "fffffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "affffff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); - final AttributeDefinition attributeDef7 = AttributeDefinition.builder() - .friendlyName(Constants.eIDAS_ATTR_BIRTHNAME).nameUri(new URI("ad", "sd", "ffffffff")) - .personType(PersonType.LEGAL_PERSON).xmlType(new QName("http://saf", "as", "afffffff")) - .attributeValueMarshaller("eu.eidas.auth.commons.attribute.impl.LiteralStringAttributeValueMarshaller").build(); ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() - .put(attributeDef, identifier) - .put(attributeDef2, familyName) - .put(attributeDef3, givenName) - .put(attributeDef4, dateOfBirth); - + .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER,"ff","af"), identifier) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME,"fff","aff"), familyName) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME,"ffff","afff"), givenName) + .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH,"fffff","affff"), dateOfBirth); if (taxNumber != null) { - builder.put(attributeDef5, taxNumber); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE,"ffffff","afffff"), taxNumber); } if (birthName != null) { - builder.put(attributeDef7, birthName); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME,"fffffff","affffff"), birthName); } if (placeOfBirth != null) { - builder.put(attributeDef6, placeOfBirth); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH,"ffffffff","afffffff"), placeOfBirth); } final ImmutableAttributeMap attributeMap = builder.build(); val b = new AuthenticationResponse.Builder(); return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( - "afaf") - .attributes(attributeMap).build(); + "afaf").attributes(attributeMap).build(); + } + + private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + + ".LiteralStringAttributeValueMarshaller"); + } + + private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + + ".DateTimeAttributeValueMarshaller"); + } + + private AttributeDefinition 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(); } - private List emptyHandlers() { + private List emptyHandlers() { return new ArrayList<>(); } -- cgit v1.2.3 From aac12e564c4cb92d6c3b84d8bcdabc112acb2427 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 14:17:52 +0100 Subject: Streamline mock creation in tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 53 +++------------------- 1 file changed, 7 insertions(+), 46 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index a1dce0f2..12a0969d 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -50,7 +50,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.annotation.DirtiesContext; @@ -69,13 +71,14 @@ import java.util.List; import java.util.Random; @RunWith(SpringJUnit4ClassRunner.class) - @ContextConfiguration("/SpringTest-context_tasks_test.xml") @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskFirstTest { private InitialSearchTask task; + @Mock private IZmrClient zmrClient; + @Mock private IErnpClient ernpClient; final ExecutionContext executionContext = new ExecutionContextImpl(); @@ -108,6 +111,9 @@ public class InitialSearchTaskFirstTest { */ @Before public void setUp() throws URISyntaxException, EaafStorageException { + MockitoAnnotations.initMocks(this); + task = new InitialSearchTask(new ArrayList(), ernpClient, zmrClient); + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); @@ -125,20 +131,15 @@ public class InitialSearchTaskFirstTest { * One match, but register update needed */ public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); String newFirstName = RandomStringUtils.randomAlphabetic(5); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); - - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -151,20 +152,14 @@ public class InitialSearchTaskFirstTest { * One match, but register update needed */ public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -179,18 +174,14 @@ public class InitialSearchTaskFirstTest { * Two matches found in ZMR */ public void testNode101_ManualFixNecessary_a() throws Exception { - ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -209,7 +200,6 @@ public class InitialSearchTaskFirstTest { public void testNode101_ManualFixNecessary_b() throws Exception { String randombpk = RandomStringUtils.random(5); ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); @@ -217,11 +207,8 @@ public class InitialSearchTaskFirstTest { ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), randomFamilyName, randomDate)); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); try { task.execute(pendingReq, executionContext); Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); @@ -237,19 +224,14 @@ public class InitialSearchTaskFirstTest { * One match, no register update needed */ public void testNode102_UserIdentified_a() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(12); ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -266,16 +248,11 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -296,7 +273,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -308,7 +284,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -347,7 +322,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -358,7 +332,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -399,7 +372,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -412,7 +384,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -442,7 +413,6 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); ArrayList zmrResultInitial = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); ArrayList zmrResultSpecific = new ArrayList<>(); @@ -455,7 +425,6 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); ArrayList ernpResultInitial = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); List handlers = new ArrayList<>(); @@ -478,16 +447,12 @@ public class InitialSearchTaskFirstTest { * NO match found in ZMR and ErnP with Initial search */ public void testNode105_TemporaryEnd() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - zmrClient = Mockito.mock(IZmrClient.class); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); ArrayList ernpResult = new ArrayList<>(); - ernpClient = Mockito.mock(IErnpClient.class); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - task = new InitialSearchTask(emptyHandlers(), ernpClient, zmrClient); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); @@ -562,8 +527,4 @@ public class InitialSearchTaskFirstTest { .attributeValueMarshaller(marshaller).build(); } - private List emptyHandlers() { - return new ArrayList<>(); - } - } -- cgit v1.2.3 From cd61bfbb1f865456ca609b807aaba40d6d1e13b2 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:00:43 +0100 Subject: Improve readability of test cases by using modern syntax --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 151 +++++++++------------ 1 file changed, 67 insertions(+), 84 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 12a0969d..35e2e56e 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -70,6 +70,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; +import static org.junit.Assert.assertThrows; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_tasks_test.xml") @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) @@ -82,17 +84,15 @@ public class InitialSearchTaskFirstTest { private IErnpClient ernpClient; final ExecutionContext executionContext = new ExecutionContextImpl(); - private MockHttpServletRequest httpReq; - private MockHttpServletResponse httpResp; private TestRequestImpl pendingReq; - private String randomIdentifier = RandomStringUtils.randomNumeric(10); - private String randomFamilyName = RandomStringUtils.randomNumeric(11); - private String randomGivenName = RandomStringUtils.randomNumeric(12); - private String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); - private String randomBirthName = RandomStringUtils.randomNumeric(12); - private String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); - private String DE_ST = "de/st/"; - private String IT_ST = "it/st/"; + private final String randomIdentifier = RandomStringUtils.randomNumeric(10); + private final String randomFamilyName = RandomStringUtils.randomNumeric(11); + private final String randomGivenName = RandomStringUtils.randomNumeric(12); + private final String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); + private final String randomBirthName = RandomStringUtils.randomNumeric(12); + private final String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); + private final String DE_ST = "de/st/"; + private final String IT_ST = "it/st/"; /** * jUnit class initializer. @@ -112,10 +112,10 @@ public class InitialSearchTaskFirstTest { @Before public void setUp() throws URISyntaxException, EaafStorageException { MockitoAnnotations.initMocks(this); - task = new InitialSearchTask(new ArrayList(), ernpClient, zmrClient); + task = new InitialSearchTask(new ArrayList<>(), ernpClient, zmrClient); - httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); - httpResp = new MockHttpServletResponse(); + MockHttpServletRequest httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + MockHttpServletResponse httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); @@ -125,11 +125,11 @@ public class InitialSearchTaskFirstTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); } - @Test - @DirtiesContext /** * One match, but register update needed */ + @Test + @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); @@ -143,14 +143,14 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * One match, but register update needed */ + @Test + @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { ArrayList zmrResult = new ArrayList<>(); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); @@ -163,17 +163,16 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); - + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * Two matches found in ZMR */ - public void testNode101_ManualFixNecessary_a() throws Exception { + @Test + @DirtiesContext + public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); @@ -182,22 +181,19 @@ public class InitialSearchTaskFirstTest { ArrayList ernpResult = new ArrayList<>(); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - try { - task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } - @Test - @DirtiesContext /** * Two matches found in ErnP */ - public void testNode101_ManualFixNecessary_b() throws Exception { + @Test + @DirtiesContext + public void testNode101_ManualFixNecessary_b() { String randombpk = RandomStringUtils.random(5); ArrayList zmrResult = new ArrayList<>(); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); @@ -209,20 +205,17 @@ public class InitialSearchTaskFirstTest { randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - try { - task.execute(pendingReq, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } - @Test - @DirtiesContext /** * One match, no register update needed */ + @Test + @DirtiesContext public void testNode102_UserIdentified_a() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(12); ArrayList zmrResult = new ArrayList<>(); @@ -235,14 +228,14 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * One match, no register update needed */ + @Test + @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(14); @@ -256,14 +249,14 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(randomBpk)); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - @Test - @DirtiesContext /** * One match found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode103_UserIdentified_IT() throws Exception { String bpkRegister = RandomStringUtils.randomNumeric(14); String taxNumber = RandomStringUtils.randomNumeric(14); @@ -291,22 +284,18 @@ public class InitialSearchTaskFirstTest { handlers.add(it); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); + task.execute(pendingReq1, executionContext); - String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(bpkRegister)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + String bPk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, bpkRegister); } - @Test - @DirtiesContext /** * Multiple matches found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode103_UserIdentified_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; @@ -339,22 +328,18 @@ public class InitialSearchTaskFirstTest { handlers.add(de); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); + task.execute(pendingReq1, executionContext); - String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertTrue("Wrong bpk", bPk.equals(bpk)); - } catch (final TaskExecutionException e) { - Assert.assertTrue("Wrong workflow, should not reach this point", false); - } + String bPk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, bpk); } - @Test - @DirtiesContext /** * Multiple matches found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode104_ManualFixNecessary_DE() throws Exception { String givenName = randomGivenName; String familyName = randomFamilyName; @@ -393,20 +378,20 @@ public class InitialSearchTaskFirstTest { try { task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); + Assert.fail("Wrong workflow, should not reach this point/ get a bpk"); } catch (final TaskExecutionException e) { Throwable origE = e.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } } - @Test - @DirtiesContext /** * Multiple matches found in ZMR and ErnP with detail search */ + @Test + @DirtiesContext public void testNode104_ManualFixNecessary_IT() throws Exception { - String fakeTaxNumber = RandomStringUtils.randomNumeric(14);; + String fakeTaxNumber = RandomStringUtils.randomNumeric(14); final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) @@ -432,20 +417,18 @@ public class InitialSearchTaskFirstTest { handlers.add(it); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); - Assert.assertTrue("Wrong workflow, should not reach this point/ get a bpk", false); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } - @Test - @DirtiesContext /** * NO match found in ZMR and ErnP with Initial search */ + @Test + @DirtiesContext public void testNode105_TemporaryEnd() throws TaskExecutionException { ArrayList zmrResult = new ArrayList<>(); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); @@ -509,17 +492,17 @@ public class InitialSearchTaskFirstTest { "afaf").attributes(attributeMap).build(); } - private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".LiteralStringAttributeValueMarshaller"); } - private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".DateTimeAttributeValueMarshaller"); } - private AttributeDefinition generateAttribute(String friendlyName, String fragment, String prefix, + private AttributeDefinition generateAttribute(String friendlyName, String fragment, String prefix, String marshaller) throws URISyntaxException { return AttributeDefinition.builder() .friendlyName(friendlyName).nameUri(new URI("ad", "sd", fragment)) -- cgit v1.2.3 From a344ab3231dd8f6c99e2e7369789aa97681f719f Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:08:17 +0100 Subject: Use generic list types in parameters and return types List instead of ArrayList allows for easier mocking and stubbing --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 55 +++++++--------------- 1 file changed, 17 insertions(+), 38 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 35e2e56e..1f512354 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -67,6 +67,7 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Random; @@ -136,9 +137,7 @@ public class InitialSearchTaskFirstTest { String newFirstName = RandomStringUtils.randomAlphabetic(5); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) @@ -152,9 +151,7 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); @@ -177,9 +174,7 @@ public class InitialSearchTaskFirstTest { zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); @@ -195,9 +190,7 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode101_ManualFixNecessary_b() { String randombpk = RandomStringUtils.random(5); - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), @@ -218,8 +211,7 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode102_UserIdentified_a() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(12); - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); @@ -242,9 +234,7 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) @@ -265,8 +255,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpkRegister, IT_ST+randomIdentifier+RandomStringUtils.random(2), @@ -276,8 +265,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -310,8 +298,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, @@ -320,8 +307,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -356,8 +342,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, @@ -368,8 +353,7 @@ public class InitialSearchTaskFirstTest { null, null)); Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -397,8 +381,7 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - ArrayList zmrResultInitial = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResultInitial); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, @@ -409,8 +392,7 @@ public class InitialSearchTaskFirstTest { fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - ArrayList ernpResultInitial = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResultInitial); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); List handlers = new ArrayList<>(); ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); @@ -430,11 +412,8 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode105_TemporaryEnd() throws TaskExecutionException { - ArrayList zmrResult = new ArrayList<>(); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - - ArrayList ernpResult = new ArrayList<>(); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) -- cgit v1.2.3 From 111dd0f0a90a31488d1d9820cb877aeddade4bf7 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:13:47 +0100 Subject: Use random values in tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 111 +++++++++------------ 1 file changed, 47 insertions(+), 64 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 1f512354..c18dabb9 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -87,10 +87,10 @@ public class InitialSearchTaskFirstTest { final ExecutionContext executionContext = new ExecutionContextImpl(); private TestRequestImpl pendingReq; private final String randomIdentifier = RandomStringUtils.randomNumeric(10); - private final String randomFamilyName = RandomStringUtils.randomNumeric(11); - private final String randomGivenName = RandomStringUtils.randomNumeric(12); - private final String randomPlaceOfBirth = RandomStringUtils.randomNumeric(12); - private final String randomBirthName = RandomStringUtils.randomNumeric(12); + private final String randomFamilyName = RandomStringUtils.randomAlphabetic(10); + private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); + private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); + private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); private final String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); private final String DE_ST = "de/st/"; private final String IT_ST = "it/st/"; @@ -154,7 +154,8 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); - ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, "Max_new", randomFamilyName, randomDate)); + String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); + ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); task.execute(pendingReq, executionContext); @@ -172,7 +173,8 @@ public class InitialSearchTaskFirstTest { public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, "Maximilian", randomFamilyName, randomDate)); + String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -189,13 +191,12 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode101_ManualFixNecessary_b() { - String randombpk = RandomStringUtils.random(5); + String randombpk = RandomStringUtils.randomNumeric(5); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName+RandomStringUtils.random(2), - randomFamilyName, - randomDate)); + String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); TaskExecutionException exception = assertThrows(TaskExecutionException.class, @@ -258,10 +259,9 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpkRegister, IT_ST+randomIdentifier+RandomStringUtils.random(2), - randomGivenName, - randomFamilyName, - randomDate, null, null, taxNumber, null)); + String newRandomPseudonym = IT_ST + randomIdentifier + RandomStringUtils.randomNumeric(2); + zmrResultSpecific.add(new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, + randomDate, null, null, taxNumber, null)); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); @@ -285,15 +285,10 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode103_UserIdentified_DE() throws Exception { - String givenName = randomGivenName; - String familyName = randomFamilyName; - String pseudonym = DE_ST + RandomStringUtils.random(5); - String bpk = RandomStringUtils.random(5); - String dateOfBirth = randomDate; - String placeOfBirth = randomPlaceOfBirth; - String birthName = randomBirthName; - final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym, - dateOfBirth, placeOfBirth, birthName); + String randomPseudonym = DE_ST + RandomStringUtils.randomNumeric(5); + String randomBpk = RandomStringUtils.randomNumeric(5); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); @@ -301,11 +296,11 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk, pseudonym, givenName, familyName, dateOfBirth, placeOfBirth, - birthName, - null, null)); + zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName,null, null)); - Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -316,9 +311,9 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq1, executionContext); - String bPk = (String) + String resultBpk = (String) pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", bPk, bpk); + Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); } /** @@ -327,17 +322,12 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode104_ManualFixNecessary_DE() throws Exception { - String givenName = randomGivenName; - String familyName = randomFamilyName; - String pseudonym1 = DE_ST + RandomStringUtils.random(5); - String pseudonym2 = pseudonym1 + RandomStringUtils.random(2); - String bpk1 = RandomStringUtils.random(5); - String bpk2 = bpk1 + RandomStringUtils.random(2); - String dateOfBirth = randomDate; - String placeOfBirth = randomPlaceOfBirth; - String birthName = randomBirthName; - final AuthenticationResponse response = buildDummyAuthResponseDE(givenName, familyName, pseudonym1, - dateOfBirth, placeOfBirth, birthName); + String pseudonym1 = DE_ST + RandomStringUtils.randomNumeric(5); + String pseudonym2 = pseudonym1 + RandomStringUtils.randomNumeric(2); + String bpk1 = RandomStringUtils.randomNumeric(5); + String bpk2 = bpk1 + RandomStringUtils.randomNumeric(2); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, pseudonym1, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); @@ -345,13 +335,12 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, givenName, familyName, dateOfBirth, placeOfBirth, - birthName, - null, null)); - zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, givenName, familyName, dateOfBirth, placeOfBirth, - birthName, - null, null)); - Mockito.when(zmrClient.searchDeSpecific(givenName, familyName, dateOfBirth, placeOfBirth, birthName)).thenReturn(zmrResultSpecific); + zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName,null, null)); + zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName,null, null)); + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -360,13 +349,10 @@ public class InitialSearchTaskFirstTest { handlers.add(de); task = new InitialSearchTask(handlers, ernpClient, zmrClient); - try { - task.execute(pendingReq1, executionContext); - Assert.fail("Wrong workflow, should not reach this point/ get a bpk"); - } catch (final TaskExecutionException e) { - Throwable origE = e.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } /** @@ -384,12 +370,10 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, - randomDate, null, null, - fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, randomFamilyName, - randomDate, null, null, - fakeTaxNumber, null)); + zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, + randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); + zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, + randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -424,13 +408,12 @@ public class InitialSearchTaskFirstTest { @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, - DE_ST+randomIdentifier, randomDate); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST+randomIdentifier, randomDate); } private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, - IT_ST+randomIdentifier, randomDate, taxNumber, null, null); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST+randomIdentifier, randomDate, + taxNumber, null, null); } @NotNull -- cgit v1.2.3 From 4e3c7bf6fba4bb38c286ab901a41b1d429db38f4 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:25:51 +0100 Subject: Use clear Arrange-Act-Assert structure in tests --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 88 ++++++++-------------- 1 file changed, 31 insertions(+), 57 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index c18dabb9..99764aad 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -135,13 +135,15 @@ public class InitialSearchTaskFirstTest { ArrayList zmrResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); String newFirstName = RandomStringUtils.randomAlphabetic(5); - zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newFirstName, randomFamilyName, randomDate)); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); + String randomPseudonym = DE_ST + randomIdentifier; + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, randomPseudonym, newFirstName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -152,19 +154,18 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList ernpResult = new ArrayList<>(); String randomBpk = RandomStringUtils.randomNumeric(6); String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); - ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } - /** * Two matches found in ZMR */ @@ -180,6 +181,7 @@ public class InitialSearchTaskFirstTest { TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -201,6 +203,7 @@ public class InitialSearchTaskFirstTest { TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -213,10 +216,8 @@ public class InitialSearchTaskFirstTest { public void testNode102_UserIdentified_a() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(12); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - ArrayList ernpResult = new ArrayList<>(); - ernpResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) @@ -231,13 +232,12 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { String randomBpk = RandomStringUtils.randomNumeric(14); - - ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); + String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); @@ -255,22 +255,14 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - String newRandomPseudonym = IT_ST + randomIdentifier + RandomStringUtils.randomNumeric(2); - zmrResultSpecific.add(new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, - randomDate, null, null, taxNumber, null)); - - Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(zmrResultSpecific); - + Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( + new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, + randomDate, null, null, taxNumber, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(it); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); + task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); @@ -292,22 +284,14 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - - zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName,null, null)); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)).thenReturn(zmrResultSpecific); - + randomBirthName)) + .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(de); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); + task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); @@ -331,26 +315,21 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null)); zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null)); Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - DeSpecificDetailSearchProcessor de = new DeSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(de); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); + task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -366,26 +345,20 @@ public class InitialSearchTaskFirstTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - List handlers = new ArrayList<>(); - ItSpecificDetailSearchProcessor it = new ItSpecificDetailSearchProcessor(ernpClient, zmrClient); - handlers.add(it); - task = new InitialSearchTask(handlers, ernpClient, zmrClient); - + task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); + Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); } @@ -400,6 +373,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); + String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); -- cgit v1.2.3 From 2d804b8233f9f92feb83c700e7dc6a2bd7f70998 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Tue, 12 Jan 2021 15:50:57 +0100 Subject: Rename variables in test for better readability --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 177 +++++++++++---------- 1 file changed, 94 insertions(+), 83 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 99764aad..9f58ba71 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -28,7 +28,6 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.RegisterResult; import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.CountrySpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; @@ -68,7 +67,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; -import java.util.List; import java.util.Random; import static org.junit.Assert.assertThrows; @@ -78,6 +76,9 @@ import static org.junit.Assert.assertThrows; @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskFirstTest { + private static final String DE_ST = "de/st/"; + private static final String IT_ST = "it/st/"; + private InitialSearchTask task; @Mock private IZmrClient zmrClient; @@ -86,14 +87,14 @@ public class InitialSearchTaskFirstTest { final ExecutionContext executionContext = new ExecutionContextImpl(); private TestRequestImpl pendingReq; + private final String randomBpk = RandomStringUtils.randomNumeric(6); private final String randomIdentifier = RandomStringUtils.randomNumeric(10); + private final String randomPseudonym = DE_ST + randomIdentifier; private final String randomFamilyName = RandomStringUtils.randomAlphabetic(10); private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); - private final String randomDate = "2011-01-"+ (10 + new Random().nextInt(18)); - private final String DE_ST = "de/st/"; - private final String IT_ST = "it/st/"; + private final String randomDate = "2011-01-" + (10 + new Random().nextInt(18)); /** * jUnit class initializer. @@ -132,17 +133,15 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - ArrayList zmrResult = new ArrayList<>(); - String randomBpk = RandomStringUtils.randomNumeric(6); - String newFirstName = RandomStringUtils.randomAlphabetic(5); - String randomPseudonym = DE_ST + randomIdentifier; + String newFirstName = RandomStringUtils.randomAlphabetic(10); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomPseudonym, newFirstName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, newFirstName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -154,14 +153,14 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - String randomBpk = RandomStringUtils.randomNumeric(6); String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -173,14 +172,14 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - zmrResult.add(new RegisterResult("bpkMax", DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); + () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -193,16 +192,16 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode101_ManualFixNecessary_b() { - String randombpk = RandomStringUtils.randomNumeric(5); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); - ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - ernpResult.add(new RegisterResult(randombpk, DE_ST+randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + ernpResult.add( + new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); + () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -214,14 +213,14 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode102_UserIdentified_a() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(12); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -231,15 +230,15 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { - String randomBpk = RandomStringUtils.randomNumeric(14); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, DE_ST+randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -249,7 +248,6 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode103_UserIdentified_IT() throws Exception { - String bpkRegister = RandomStringUtils.randomNumeric(14); String taxNumber = RandomStringUtils.randomNumeric(14); final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); @@ -258,17 +256,19 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); String newRandomPseudonym = IT_ST + randomIdentifier + RandomStringUtils.randomNumeric(2); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( - new RegisterResult(bpkRegister, newRandomPseudonym, randomGivenName, randomFamilyName, - randomDate, null, null, taxNumber, null))); + new RegisterResult(randomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, + randomDate, null, null, taxNumber, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", bPk, bpkRegister); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); } /** @@ -277,26 +277,27 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode103_UserIdentified_DE() throws Exception { - String randomPseudonym = DE_ST + RandomStringUtils.randomNumeric(5); - String randomBpk = RandomStringUtils.randomNumeric(5); - final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, randomPseudonym, - randomDate, randomPlaceOfBirth, randomBirthName); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, + randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)) - .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, - randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName,null, null))); + randomBirthName)) + .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); task.execute(pendingReq1, executionContext); String resultBpk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); } @@ -306,29 +307,30 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode104_ManualFixNecessary_DE() throws Exception { - String pseudonym1 = DE_ST + RandomStringUtils.randomNumeric(5); - String pseudonym2 = pseudonym1 + RandomStringUtils.randomNumeric(2); - String bpk1 = RandomStringUtils.randomNumeric(5); - String bpk2 = bpk1 + RandomStringUtils.randomNumeric(2); - final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, pseudonym1, - randomDate, randomPlaceOfBirth, randomBirthName); + String newRandomPseudonym = randomPseudonym + RandomStringUtils.randomNumeric(2); + String newRandomBpk = randomBpk + RandomStringUtils.randomNumeric(6); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, + randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult(bpk1, pseudonym1, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName,null, null)); - zmrResultSpecific.add(new RegisterResult(bpk2, pseudonym2, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName,null, null)); + zmrResultSpecific.add( + new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName, null, null)); + zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName, null, null)); Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)).thenReturn(zmrResultSpecific); + randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq1, executionContext)); + () -> task.execute(pendingReq1, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -340,24 +342,28 @@ public class InitialSearchTaskFirstTest { @Test @DirtiesContext public void testNode104_ManualFixNecessary_IT() throws Exception { - String fakeTaxNumber = RandomStringUtils.randomNumeric(14); - final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(fakeTaxNumber); + String randomTaxNumber = RandomStringUtils.randomNumeric(14); + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(randomTaxNumber); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add(new RegisterResult("bpkMax", IT_ST+randomIdentifier+"4", randomGivenName, - randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); - zmrResultSpecific.add(new RegisterResult("bpkMax1", IT_ST+randomIdentifier+"5", randomGivenName, - randomFamilyName, randomDate, null, null, fakeTaxNumber, null)); - Mockito.when(zmrClient.searchItSpecific(fakeTaxNumber)).thenReturn(zmrResultSpecific); + String randomPseudonym = IT_ST + randomIdentifier + "4"; + zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + String newRandomPseudonym = IT_ST + randomIdentifier + "5"; + String newRandomBpk = RandomStringUtils.randomNumeric(6); + zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, + randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + Mockito.when(zmrClient.searchItSpecific(randomTaxNumber)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask(Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + task = new InitialSearchTask( + Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq1, executionContext)); + () -> task.execute(pendingReq1, executionContext)); Throwable origE = exception.getOriginalException(); Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); @@ -375,19 +381,21 @@ public class InitialSearchTaskFirstTest { task.execute(pendingReq, executionContext); String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); } @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST+randomIdentifier, randomDate); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomIdentifier, randomDate); } - private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST+randomIdentifier, randomDate, - taxNumber, null, null); + private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) + throws URISyntaxException { + return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST + randomIdentifier, randomDate, + taxNumber, null, null); } @NotNull @@ -408,18 +416,19 @@ public class InitialSearchTaskFirstTest { String dateOfBirth, String taxNumber, String placeOfBirth, String birthName) throws URISyntaxException { ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() - .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER,"ff","af"), identifier) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME,"fff","aff"), familyName) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME,"ffff","afff"), givenName) - .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH,"fffff","affff"), dateOfBirth); + .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER, "ff", "af"), identifier) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, "fff", "aff"), familyName) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME, "ffff", "afff"), givenName) + .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH, "fffff", "affff"), dateOfBirth); if (taxNumber != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE,"ffffff","afffff"), taxNumber); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE, "ffffff", "afffff"), taxNumber); } if (birthName != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME,"fffffff","affffff"), birthName); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME, "fffffff", "affffff"), birthName); } if (placeOfBirth != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH,"ffffffff","afffffff"), placeOfBirth); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH, "ffffffff", "afffffff"), + placeOfBirth); } final ImmutableAttributeMap attributeMap = builder.build(); @@ -428,18 +437,20 @@ public class InitialSearchTaskFirstTest { "afaf").attributes(attributeMap).build(); } - private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) + throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".LiteralStringAttributeValueMarshaller"); } - private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { + private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) + throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + ".DateTimeAttributeValueMarshaller"); } private AttributeDefinition generateAttribute(String friendlyName, String fragment, String prefix, - String marshaller) throws URISyntaxException { + 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)) -- cgit v1.2.3 From b9f95d7008eca05ef26229725e7fed709fac4a10 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 15 Jan 2021 15:50:31 +0100 Subject: fix merge problem in EidasResponseUtils.java refactor broken jUnit test InitialSearchTaskFirstTest.java to new configuration-loader --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 72 ++++++++++------------ 1 file changed, 32 insertions(+), 40 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 9f58ba71..f1bc98d6 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -23,6 +23,34 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; +import static org.junit.Assert.assertThrows; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Random; + +import javax.xml.namespace.QName; + +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +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 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.ernp.IErnpClient; @@ -42,37 +70,12 @@ import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; import eu.eidas.auth.commons.attribute.PersonType; import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; import lombok.val; -import org.apache.commons.lang3.RandomStringUtils; -import org.jetbrains.annotations.NotNull; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -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.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Random; - -import static org.junit.Assert.assertThrows; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("/SpringTest-context_tasks_test.xml") +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" +}) @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskFirstTest { @@ -96,17 +99,6 @@ public class InitialSearchTaskFirstTest { private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); private final String randomDate = "2011-01-" + (10 + new Random().nextInt(18)); - /** - * jUnit class initializer. - * - * @throws IOException In case of an error - */ - @BeforeClass - public static void classInitializer() throws IOException { - final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current - + "src/test/resources/config/junit_config_1.properties"); - } /** * jUnit test set-up. -- cgit v1.2.3 From 09751b59f7e2da247c32324826607e5f1eef0f10 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 15 Jan 2021 16:56:29 +0100 Subject: fix for test102* --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java index 9f58ba71..62c00813 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java @@ -135,7 +135,7 @@ public class InitialSearchTaskFirstTest { public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { String newFirstName = RandomStringUtils.randomAlphabetic(10); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomPseudonym, newFirstName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, newFirstName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); @@ -155,7 +155,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) @@ -172,9 +172,9 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - zmrResult.add(new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -197,7 +197,7 @@ public class InitialSearchTaskFirstTest { ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); ernpResult.add( - new RegisterResult(randomBpk, randomPseudonym, newRandomGivenName, randomFamilyName, randomDate)); + new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); TaskExecutionException exception = assertThrows(TaskExecutionException.class, @@ -215,7 +215,7 @@ public class InitialSearchTaskFirstTest { public void testNode102_UserIdentified_a() throws Exception { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); task.execute(pendingReq, executionContext); String bPk = (String) @@ -231,7 +231,7 @@ public class InitialSearchTaskFirstTest { @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); @@ -254,9 +254,9 @@ public class InitialSearchTaskFirstTest { pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - String newRandomPseudonym = IT_ST + randomIdentifier + RandomStringUtils.randomNumeric(2); + String newRandomIdentifier = randomIdentifier + RandomStringUtils.randomNumeric(2); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, + new RegisterResult(randomBpk, newRandomIdentifier, randomGivenName, randomFamilyName, randomDate, null, null, taxNumber, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( @@ -286,7 +286,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName)) - .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( @@ -318,7 +318,7 @@ public class InitialSearchTaskFirstTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add( - new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate, + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null)); zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null)); -- cgit v1.2.3 From 4c621edbacbaed95edf4cac3a44a84e9e5c55819 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 29 Jan 2021 17:11:32 +0100 Subject: remove unnecessary classes --- .../v2/test/tasks/InitialSearchTaskFirstTest.java | 463 --------------------- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 463 +++++++++++++++++++++ 2 files changed, 463 insertions(+), 463 deletions(-) delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java deleted file mode 100644 index f2dc6d55..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskFirstTest.java +++ /dev/null @@ -1,463 +0,0 @@ -/* - * 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.dao.RegisterResult; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; -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.protocol.impl.AuthenticationResponse; -import lombok.val; -import org.apache.commons.lang3.RandomStringUtils; -import org.jetbrains.annotations.NotNull; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -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.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Random; - -import static org.junit.Assert.assertThrows; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "/SpringTest-context_tasks_test.xml", - "/SpringTest-context_basic_mapConfig.xml" -}) -@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) -public class InitialSearchTaskFirstTest { - - private static final String DE_ST = "de/st/"; - private static final String IT_ST = "it/st/"; - - private InitialSearchTask task; - @Mock - private IZmrClient zmrClient; - @Mock - private IErnpClient ernpClient; - - final ExecutionContext executionContext = new ExecutionContextImpl(); - private TestRequestImpl pendingReq; - private final String randomBpk = RandomStringUtils.randomNumeric(6); - private final String randomIdentifier = RandomStringUtils.randomNumeric(10); - private final String randomPseudonym = DE_ST + randomIdentifier; - private final String randomFamilyName = RandomStringUtils.randomAlphabetic(10); - private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); - private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); - private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); - private final String randomDate = "2011-01-" + (10 + new Random().nextInt(18)); - -// /** -// * jUnit class initializer. -// * -// * @throws IOException In case of an error -// */ -// @BeforeClass -// public static void classInitializer() throws IOException { -// final String current = new java.io.File(".").toURI().toString(); -// System.setProperty("eidas.ms.configuration", current -// + "src/test/resources/config/junit_config_1.properties"); -// } - - /** - * jUnit test set-up. - */ - @Before - public void setUp() throws URISyntaxException, EaafStorageException { - MockitoAnnotations.initMocks(this); - task = new InitialSearchTask(new ArrayList<>(), ernpClient, zmrClient); - - 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); - } - - /** - * One match, but register update needed - */ - @Test - @DirtiesContext - public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - String newFirstName = RandomStringUtils.randomAlphabetic(10); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, newFirstName, randomFamilyName, randomDate))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - - Assert.assertEquals("Wrong bpk", bPk, randomBpk); - } - - /** - * One match, but register update needed - */ - @Test - @DirtiesContext - public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); - - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - - Assert.assertEquals("Wrong bpk", bPk, randomBpk); - } - - /** - * Two matches found in ZMR - */ - @Test - @DirtiesContext - public void testNode101_ManualFixNecessary_a() { - ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate)); - String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } - - - /** - * Two matches found in ErnP - */ - @Test - @DirtiesContext - public void testNode101_ManualFixNecessary_b() { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList ernpResult = new ArrayList<>(); - ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); - String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - ernpResult.add( - new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); - - TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } - - /** - * One match, no register update needed - */ - @Test - @DirtiesContext - public void testNode102_UserIdentified_a() throws Exception { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); - - task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); - } - - /** - * One match, no register update needed - */ - @Test - @DirtiesContext - public void testNode102_UserIdentified_b() throws Exception { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - task.execute(pendingReq, executionContext); - - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); - } - - /** - * One match found in ZMR and ErnP with detail search - */ - @Test - @DirtiesContext - public void testNode103_UserIdentified_IT() throws Exception { - String taxNumber = RandomStringUtils.randomNumeric(14); - final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); - TestRequestImpl pendingReq1 = new TestRequestImpl(); - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - String newRandomIdentifier = randomIdentifier + RandomStringUtils.randomNumeric(2); - Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, newRandomIdentifier, randomGivenName, randomFamilyName, - randomDate, null, null, taxNumber, null))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); - - task.execute(pendingReq1, executionContext); - - String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); - } - - /** - * Multiple matches found in ZMR and ErnP with detail search - */ - @Test - @DirtiesContext - public void testNode103_UserIdentified_DE() throws Exception { - final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, - randomPseudonym, - randomDate, randomPlaceOfBirth, randomBirthName); - TestRequestImpl pendingReq1 = new TestRequestImpl(); - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)) - .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, - randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); - - task.execute(pendingReq1, executionContext); - - String resultBpk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); - } - - /** - * Multiple matches found in ZMR and ErnP with detail search - */ - @Test - @DirtiesContext - public void testNode104_ManualFixNecessary_DE() throws Exception { - String newRandomPseudonym = randomPseudonym + RandomStringUtils.randomNumeric(2); - String newRandomBpk = randomBpk + RandomStringUtils.randomNumeric(6); - final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, - randomPseudonym, - randomDate, randomPlaceOfBirth, randomBirthName); - TestRequestImpl pendingReq1 = new TestRequestImpl(); - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName, null, null)); - zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomDate, - randomPlaceOfBirth, randomBirthName, null, null)); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, - randomBirthName)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); - - TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq1, executionContext)); - - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } - - /** - * Multiple matches found in ZMR and ErnP with detail search - */ - @Test - @DirtiesContext - public void testNode104_ManualFixNecessary_IT() throws Exception { - String randomTaxNumber = RandomStringUtils.randomNumeric(14); - final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(randomTaxNumber); - TestRequestImpl pendingReq1 = new TestRequestImpl(); - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - String randomPseudonym = IT_ST + randomIdentifier + "4"; - zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, - randomFamilyName, randomDate, null, null, randomTaxNumber, null)); - String newRandomPseudonym = IT_ST + randomIdentifier + "5"; - String newRandomBpk = RandomStringUtils.randomNumeric(6); - zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, - randomFamilyName, randomDate, null, null, randomTaxNumber, null)); - Mockito.when(zmrClient.searchItSpecific(randomTaxNumber)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); - - TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq1, executionContext)); - - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); - } - - /** - * NO match found in ZMR and ErnP with Initial search - */ - @Test - @DirtiesContext - public void testNode105_TemporaryEnd() throws TaskExecutionException { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - task.execute(pendingReq, executionContext); - - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); - } - - - @NotNull - private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomIdentifier, randomDate); - } - - private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) - throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST + randomIdentifier, randomDate, - taxNumber, null, null); - } - - @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, "ff", "af"), identifier) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, "fff", "aff"), familyName) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME, "ffff", "afff"), givenName) - .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH, "fffff", "affff"), dateOfBirth); - if (taxNumber != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE, "ffffff", "afffff"), taxNumber); - } - if (birthName != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME, "fffffff", "affffff"), birthName); - } - if (placeOfBirth != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH, "ffffffff", "afffffff"), - placeOfBirth); - } - final ImmutableAttributeMap attributeMap = builder.build(); - - val b = new AuthenticationResponse.Builder(); - return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( - "afaf").attributes(attributeMap).build(); - } - - private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) - throws URISyntaxException { - return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + - ".LiteralStringAttributeValueMarshaller"); - } - - private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) - throws URISyntaxException { - return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + - ".DateTimeAttributeValueMarshaller"); - } - - private AttributeDefinition 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/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..ac188cda --- /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,463 @@ +/* + * 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.dao.RegisterResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; +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.protocol.impl.AuthenticationResponse; +import lombok.val; +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +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.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Random; + +import static org.junit.Assert.assertThrows; + +@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 DE_ST = "de/st/"; + private static final String IT_ST = "it/st/"; + + private InitialSearchTask task; + @Mock + private IZmrClient zmrClient; + @Mock + private IErnpClient ernpClient; + + final ExecutionContext executionContext = new ExecutionContextImpl(); + private TestRequestImpl pendingReq; + private final String randomBpk = RandomStringUtils.randomNumeric(6); + private final String randomIdentifier = RandomStringUtils.randomNumeric(10); + private final String randomPseudonym = DE_ST + randomIdentifier; + private final String randomFamilyName = RandomStringUtils.randomAlphabetic(10); + private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); + private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); + private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); + private final String randomDate = "2011-01-" + (10 + new Random().nextInt(18)); + +// /** +// * jUnit class initializer. +// * +// * @throws IOException In case of an error +// */ +// @BeforeClass +// public static void classInitializer() throws IOException { +// final String current = new java.io.File(".").toURI().toString(); +// System.setProperty("eidas.ms.configuration", current +// + "src/test/resources/config/junit_config_1.properties"); +// } + + /** + * jUnit test set-up. + */ + @Before + public void setUp() throws URISyntaxException, EaafStorageException { + MockitoAnnotations.initMocks(this); + task = new InitialSearchTask(new ArrayList<>(), ernpClient, zmrClient); + + 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); + } + + /** + * One match, but register update needed + */ + @Test + @DirtiesContext + public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { + String newFirstName = RandomStringUtils.randomAlphabetic(10); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, randomIdentifier, newFirstName, randomFamilyName, randomDate))); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + + Assert.assertEquals("Wrong bpk", bPk, randomBpk); + } + + /** + * One match, but register update needed + */ + @Test + @DirtiesContext + public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); + + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + + Assert.assertEquals("Wrong bpk", bPk, randomBpk); + } + + /** + * Two matches found in ZMR + */ + @Test + @DirtiesContext + public void testNode101_ManualFixNecessary_a() { + ArrayList zmrResult = new ArrayList<>(); + zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + + + /** + * Two matches found in ErnP + */ + @Test + @DirtiesContext + public void testNode101_ManualFixNecessary_b() { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + ArrayList ernpResult = new ArrayList<>(); + ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); + String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + ernpResult.add( + new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + + /** + * One match, no register update needed + */ + @Test + @DirtiesContext + public void testNode102_UserIdentified_a() throws Exception { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + + task.execute(pendingReq, executionContext); + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); + } + + /** + * One match, no register update needed + */ + @Test + @DirtiesContext + public void testNode102_UserIdentified_b() throws Exception { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); + } + + /** + * One match found in ZMR and ErnP with detail search + */ + @Test + @DirtiesContext + public void testNode103_UserIdentified_IT() throws Exception { + String taxNumber = RandomStringUtils.randomNumeric(14); + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + String newRandomIdentifier = randomIdentifier + RandomStringUtils.randomNumeric(2); + Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( + new RegisterResult(randomBpk, newRandomIdentifier, randomGivenName, randomFamilyName, + randomDate, null, null, taxNumber, null))); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + task = new InitialSearchTask( + Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); + + task.execute(pendingReq1, executionContext); + + String bPk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", bPk, randomBpk); + } + + /** + * Multiple matches found in ZMR and ErnP with detail search + */ + @Test + @DirtiesContext + public void testNode103_UserIdentified_DE() throws Exception { + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, + randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + randomBirthName)) + .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, + randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null))); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + task = new InitialSearchTask( + Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); + + task.execute(pendingReq1, executionContext); + + String resultBpk = (String) + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); + } + + /** + * Multiple matches found in ZMR and ErnP with detail search + */ + @Test + @DirtiesContext + public void testNode104_ManualFixNecessary_DE() throws Exception { + String newRandomPseudonym = randomPseudonym + RandomStringUtils.randomNumeric(2); + String newRandomBpk = randomBpk + RandomStringUtils.randomNumeric(6); + final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, + randomPseudonym, + randomDate, randomPlaceOfBirth, randomBirthName); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + ArrayList zmrResultSpecific = new ArrayList<>(); + zmrResultSpecific.add( + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName, null, null)); + zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomDate, + randomPlaceOfBirth, randomBirthName, null, null)); + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + randomBirthName)).thenReturn(zmrResultSpecific); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + task = new InitialSearchTask( + Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); + + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq1, executionContext)); + + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + + /** + * Multiple matches found in ZMR and ErnP with detail search + */ + @Test + @DirtiesContext + public void testNode104_ManualFixNecessary_IT() throws Exception { + String randomTaxNumber = RandomStringUtils.randomNumeric(14); + final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(randomTaxNumber); + TestRequestImpl pendingReq1 = new TestRequestImpl(); + pendingReq1.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + ArrayList zmrResultSpecific = new ArrayList<>(); + String randomPseudonym = IT_ST + randomIdentifier + "4"; + zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, + randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + String newRandomPseudonym = IT_ST + randomIdentifier + "5"; + String newRandomBpk = RandomStringUtils.randomNumeric(6); + zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, + randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + Mockito.when(zmrClient.searchItSpecific(randomTaxNumber)).thenReturn(zmrResultSpecific); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + task = new InitialSearchTask( + Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), + ernpClient, zmrClient); + + TaskExecutionException exception = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq1, executionContext)); + + Throwable origE = exception.getOriginalException(); + Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + } + + /** + * NO match found in ZMR and ErnP with Initial search + */ + @Test + @DirtiesContext + public void testNode105_TemporaryEnd() throws TaskExecutionException { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); + } + + + @NotNull + private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { + return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomIdentifier, randomDate); + } + + private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) + throws URISyntaxException { + return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST + randomIdentifier, randomDate, + taxNumber, null, null); + } + + @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, "ff", "af"), identifier) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, "fff", "aff"), familyName) + .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME, "ffff", "afff"), givenName) + .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH, "fffff", "affff"), dateOfBirth); + if (taxNumber != null) { + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE, "ffffff", "afffff"), taxNumber); + } + if (birthName != null) { + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME, "fffffff", "affffff"), birthName); + } + if (placeOfBirth != null) { + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH, "ffffffff", "afffffff"), + placeOfBirth); + } + final ImmutableAttributeMap attributeMap = builder.build(); + + val b = new AuthenticationResponse.Builder(); + return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( + "afaf").attributes(attributeMap).build(); + } + + private AttributeDefinition generateStringAttribute(String friendlyName, String fragment, String prefix) + throws URISyntaxException { + return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + + ".LiteralStringAttributeValueMarshaller"); + } + + private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) + throws URISyntaxException { + return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + + ".DateTimeAttributeValueMarshaller"); + } + + private AttributeDefinition 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(); + } + +} -- cgit v1.2.3 From de03adfbe79968f65bb711d7b3a583eeb1054140 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Mon, 1 Feb 2021 09:42:38 +0100 Subject: more transitions & tests --- .../IdAustriaClientAuthMetadataControllerTest.java | 169 +++++++++++++++++++++ .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 131 ++++++++++++---- .../EidasRequestPreProcessingFirstTest.java | 7 +- 3 files changed, 279 insertions(+), 28 deletions(-) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataControllerTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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..c99c6e6a --- /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,169 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthCredentialProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthMetadataController; +import at.gv.egiz.eaaf.core.test.dummy.DummyAuthConfigMap; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +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.opensaml.security.x509.BasicX509Credential; +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import at.gv.egiz.eaaf.core.api.data.PvpAttributeDefinitions; +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) +//@TestPropertySource(locations = {"classpath:/config/junit_config_de_attributes.properties"}) +@TestPropertySource(locations = { "classpath:/config/junit_config_1_springboot.properties" }) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" +}) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +@Ignore +public class IdAustriaClientAuthMetadataControllerTest { + + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + + @Autowired private IdAustriaClientAuthMetadataController controller; + @Autowired private IdAustriaClientAuthCredentialProvider credProvider; + @Autowired private DummyAuthConfigMap config; + + /** + * 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(); + + config.removeConfigValue("core.legacy.allowLegacyMode"); + config.removeConfigValue("modules.eidascentralauth.semper.mandates.active"); + config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.1"); + config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.2"); + config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.3"); + config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.4"); + config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.5"); + config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.6"); + + } + + @Test + public void buildMetadataValidInEidMode() throws IOException, EaafException, + XMLParserException, UnmarshallingException, FilterException { + config.putConfigValue("core.legacy.allowLegacyMode", "false"); + config.putConfigValue("modules.eidascentralauth.semper.mandates.active", "false"); + + //build metdata + controller.getSpMetadata(httpReq, httpResp); + + //check result + validateResponse(6); + + } + + 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("ContactPersons", + metadata.getContactPersons().isEmpty()); + Assert.assertNotNull("ContactPersons", + metadata.getOrganization()); + + 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()); + + } + + private List convertX509Certs(List certs) { + final List result = new ArrayList<>(); + for (final X509Certificate cert : certs) { + result.add(new BasicX509Credential(cert)); + + } + return result; + } +} 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 index ac188cda..95986c49 100644 --- 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 @@ -46,7 +46,6 @@ import org.apache.commons.lang3.RandomStringUtils; import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -62,7 +61,6 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.xml.namespace.QName; -import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -97,7 +95,7 @@ public class InitialSearchTaskTest { private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); - private final String randomDate = "2011-01-" + (10 + new Random().nextInt(18)); + private final String randomBirthDate = "2011-01-" + (10 + new Random().nextInt(18)); // /** // * jUnit class initializer. @@ -138,7 +136,7 @@ public class InitialSearchTaskTest { public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { String newFirstName = RandomStringUtils.randomAlphabetic(10); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, newFirstName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, newFirstName, randomFamilyName, randomBirthDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); @@ -158,7 +156,7 @@ public class InitialSearchTaskTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate))); task.execute(pendingReq, executionContext); String bPk = (String) @@ -175,9 +173,9 @@ public class InitialSearchTaskTest { @DirtiesContext public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); - zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -197,10 +195,10 @@ public class InitialSearchTaskTest { public void testNode101_ManualFixNecessary_b() { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); - ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomDate)); + ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomBirthDate)); String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); ernpResult.add( - new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomDate)); + new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); TaskExecutionException exception = assertThrows(TaskExecutionException.class, @@ -218,7 +216,7 @@ public class InitialSearchTaskTest { public void testNode102_UserIdentified_a() throws Exception { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); task.execute(pendingReq, executionContext); String bPk = (String) @@ -234,7 +232,7 @@ public class InitialSearchTaskTest { @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate))); + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); @@ -260,7 +258,7 @@ public class InitialSearchTaskTest { String newRandomIdentifier = randomIdentifier + RandomStringUtils.randomNumeric(2); Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( new RegisterResult(randomBpk, newRandomIdentifier, randomGivenName, randomFamilyName, - randomDate, null, null, taxNumber, null))); + randomBirthDate, null, null, taxNumber, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), @@ -282,15 +280,15 @@ public class InitialSearchTaskTest { public void testNode103_UserIdentified_DE() throws Exception { final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, randomPseudonym, - randomDate, randomPlaceOfBirth, randomBirthName); + randomBirthDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomBirthDate, randomPlaceOfBirth, randomBirthName)) .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, - randomFamilyName, randomDate, randomPlaceOfBirth, randomBirthName, null, null))); + randomFamilyName, randomBirthDate, randomPlaceOfBirth, randomBirthName, null, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), @@ -314,18 +312,18 @@ public class InitialSearchTaskTest { String newRandomBpk = randomBpk + RandomStringUtils.randomNumeric(6); final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, randomPseudonym, - randomDate, randomPlaceOfBirth, randomBirthName); + randomBirthDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList zmrResultSpecific = new ArrayList<>(); zmrResultSpecific.add( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomDate, + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate, randomPlaceOfBirth, randomBirthName, null, null)); - zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomDate, + zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomBirthDate, randomPlaceOfBirth, randomBirthName, null, null)); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomDate, randomPlaceOfBirth, + Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomBirthDate, randomPlaceOfBirth, randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( @@ -354,11 +352,11 @@ public class InitialSearchTaskTest { ArrayList zmrResultSpecific = new ArrayList<>(); String randomPseudonym = IT_ST + randomIdentifier + "4"; zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, - randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + randomFamilyName, randomBirthDate, null, null, randomTaxNumber, null)); String newRandomPseudonym = IT_ST + randomIdentifier + "5"; String newRandomBpk = RandomStringUtils.randomNumeric(6); zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, - randomFamilyName, randomDate, null, null, randomTaxNumber, null)); + randomFamilyName, randomBirthDate, null, null, randomTaxNumber, null)); Mockito.when(zmrClient.searchItSpecific(randomTaxNumber)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( @@ -373,11 +371,11 @@ public class InitialSearchTaskTest { } /** - * NO match found in ZMR and ErnP with Initial search + * NO match found in ZMR and ErnP with Initial and MDS search */ @Test @DirtiesContext - public void testNode105_TemporaryEnd() throws TaskExecutionException { + public void testNode505_TransitionToErnbTask() throws TaskExecutionException { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -386,18 +384,99 @@ public class InitialSearchTaskTest { String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", "TODO-Temporary-Endnode-105", bPk); + Assert.assertEquals("Wrong bpk", null, bPk); + + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Assert.assertEquals("Wrong transition", null, transitionGUI); + Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); + Assert.assertEquals("Wrong transition", true, transitionErnb); + } + + /** + * NO match found in ZMR and ErnP with Initial search, one match with MDS search in Ernb + */ + @Test + @DirtiesContext + public void testNode505_TransitionToGUI_Ernb() throws TaskExecutionException { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + + Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn( + Collections.singletonList( + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); + + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", null, bPk); + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Assert.assertEquals("Wrong transition", true, transitionGUI); + Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); + Assert.assertEquals("Wrong transition", null, transitionErnb); + } + + /** + * NO match found in ZMR and ErnP with Initial search, one match with MDS search in ZMR + */ + @Test + @DirtiesContext + public void testNode505_TransitionToGUI_Zmr() throws TaskExecutionException { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + + Mockito.when(zmrClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn( + Collections.singletonList( + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); + + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", null, bPk); + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Assert.assertEquals("Wrong transition", true, transitionGUI); + Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); + Assert.assertEquals("Wrong transition", null, transitionErnb); } + /** + * NO match found in ZMR and ErnP with Initial search, multiple matches found with MDS search + */ + @Test + @DirtiesContext + public void testNode505_TransitionToGUI_Ernb_multi() throws TaskExecutionException { + Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + ArrayList ernbResult = new ArrayList<>(); + ernbResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, + randomBirthDate)); + ernbResult.add(new RegisterResult(randomBpk+"1", randomIdentifier, randomGivenName, randomFamilyName, + randomBirthDate)); + Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn(ernbResult); + + task.execute(pendingReq, executionContext); + + String bPk = (String) + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + Assert.assertEquals("Wrong bpk", null, bPk); + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Assert.assertEquals("Wrong transition", true, transitionGUI); + Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); + Assert.assertEquals("Wrong transition", null, transitionErnb); + } @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomIdentifier, randomDate); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomIdentifier, randomBirthDate); } private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST + randomIdentifier, randomDate, + return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST + randomIdentifier, randomBirthDate, taxNumber, null, null); } 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 d0ab50f4..35f1a91b 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 { -- cgit v1.2.3 From 6e16e4bbddf6dcddf2ed7b25fd55b41adfa4a08c Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 5 Feb 2021 11:58:12 +0100 Subject: added test for ReceiveLoginMethodGuiResponse --- .../ReceiveLoginMethodGuiResponseTaskTest.java | 139 +++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java new file mode 100644 index 00000000..c6729a03 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java @@ -0,0 +1,139 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SelectedLoginMethod; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveLoginMethodGuiResponseTask; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.controller.tasks.AbstractLocaleAuthServletTask; +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.Assert; +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 java.io.UnsupportedEncodingException; + +@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration({ +// "/applicationContext.xml", +// "/specific_eIDAS_connector.beans.xml", +// "/eaaf_core.beans.xml", +// "/eaaf_pvp.beans.xml", +// "/eaaf_pvp_idp.beans.xml", +// "/spring/SpringTest-context_simple_storage.xml" }) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" +}) +@ActiveProfiles(profiles = {"deprecatedConfig"}) +@WebAppConfiguration +public class ReceiveLoginMethodGuiResponseTaskTest { + + @Autowired private ReceiveLoginMethodGuiResponseTask task; + + private 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 { + test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); + } + + @Test + public void withEidasSelection() throws TaskExecutionException { + test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); + } + + @Test + public void withNoOtherLoginSelection() throws TaskExecutionException { + test(SelectedLoginMethod.NO_OTHER_LOGIN); + } + + public void test(SelectedLoginMethod loginMethod) throws TaskExecutionException { + String parameterValue = loginMethod.name(); + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); + + task.execute(pendingReq, executionContext); + + //result validation + Assert.assertFalse("wrong pendingReq auth flag", pendingReq.isAuthenticated()); + Assert.assertFalse("wrong process-cancelled flag", executionContext.isProcessCancelled()); + + Assert.assertNotNull("no login-selection found", + executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); + Assert.assertEquals("Wrong login-selection found", loginMethod, + executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); + } + + + @Test(expected = TaskExecutionException.class) + public void withInvalidSelection() throws TaskExecutionException { + String parameterValue = RandomStringUtils.randomAlphabetic(2); + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); + task.execute(pendingReq, executionContext); + } + + @Test(expected = TaskExecutionException.class) + public void withNullSelection() throws TaskExecutionException { + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, "null"); + task.execute(pendingReq, executionContext); + } + + @Test(expected = TaskExecutionException.class) + public void withEmptySelection() throws TaskExecutionException { + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, ""); + task.execute(pendingReq, executionContext); + } + + @Test(expected = TaskExecutionException.class) + public void withoutLoginMethodSelection() throws TaskExecutionException, UnsupportedEncodingException { + task.execute(pendingReq, executionContext); + } +} -- cgit v1.2.3 From 5a07ce3e84615cb088ed844312d726679095ec03 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Mon, 8 Feb 2021 13:04:07 +0100 Subject: GenerateMobilePhoneSignatureRequestTaskTest --- .../eidas/v2/test/dummy/DummyAuthConfigMap.java | 144 +++++++++ .../modules/auth/eidas/v2/test/dummy/DummyOA.java | 304 ++++++++++++++++++ .../eidas/v2/test/dummy/IAhSpConfiguration.java | 152 +++++++++ ...enerateMobilePhoneSignatureRequestTaskTest.java | 346 +++++++++++++++++++++ 4 files changed, 946 insertions(+) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyAuthConfigMap.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyOA.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/IAhSpConfiguration.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateMobilePhoneSignatureRequestTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 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 getBasicConfigurationWithPrefix(final String prefix) { + return KeyValueUtils.getSubSetWithPrefix(config, prefix); + + } + + @Override + public ISpConfiguration getServiceProviderConfiguration(final String uniqueID) + throws EaafConfigurationException { + return null; + } + + @Override + public T getServiceProviderConfiguration(final String spIdentifier, final Class 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..cf879562 --- /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 org.apache.commons.lang3.StringUtils; + +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; +import at.gv.egiz.eaaf.core.impl.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 config = new HashMap<>(); + private final List> 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> 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 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.valueOf(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 List getTargetsWithNoBaseIdInternalProcessingRestriction() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getTargetsWithNoBaseIdTransferRestriction() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List 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 getTestCredentialOids() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List> 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 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 getMandateProfiles() { + return KeyValueUtils.getListOfCsvValues(mandateProfilesCsv); + } + + @Override + public List getAdditionalBpkTargets() { + return KeyValueUtils.getListOfCsvValues(additionalBpkTargetCsv); + + } + + @Override + public List> 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> 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/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. + * + *

If no BM.I specific identifier is available then this method returns + * the same identifier as getUniqueIdentifier()

+ * + * @return unique identifier from BM.I AppReg, or generic uniqueId of no specific exists + */ + String getUniqueApplicationRegisterIdentifier(); + + /** + * Flag that marks this Service-Provider as public or private. + * + *

Default: If it is not set or has an unknown value, its private by default

+ * + * @return true if it is from public, otherwise false + */ + 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 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> getRequiredAttributes(); + + + /** + * Get the CountryCode for this service.
+ *
+ * Default: 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 true if mandates are enabled, otherwise false + */ + boolean isMandateEnabled(); + + /** + * Enables multi-mandates for this service-provider. + * + * @return true if multi-mandates are enabled, otherwise false + */ + boolean isMultiMandateEnabled(); + + /** + * Only mandates are allowed for this service provider. + * + * @return true if only mandates are allowed, otherwise false + */ + boolean isOnlyMandateEnabled(); + + /** + * Get a {@link List} of mandate profiles that are supported by this Service provider. + * + * @return + */ + @Nonnull List getMandateProfiles(); + + + /** + * eIDAS authentication allowed flag. + * + * @return true if eIDAS authentication is enabled, otherwise false + */ + 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 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> getAdditionalForeignBpkTargets(); + + /** + * Flag that indicates that service-provider as restricted or unrestricted. + * + *

A restricted service-provider can only used by test-identities that contains a + * valid application-restriction in User-Certificate Pinning

+ * + *

Default: true

+ * + * @return true if it is restricted, otherwise false + */ + 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/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..379f64ee --- /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,346 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthMetadataProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateMobilePhoneSignatureRequestTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyAuthConfigMap; +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.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.api.reqattr.EaafRequestedAttribute; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2InternalErrorException; +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 org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +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.schema.XSString; +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.TestPropertySource; +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@TestPropertySource(locations = {"classpath:/config/junit_config_1-.properties" }) +//@ContextConfiguration({"/spring/SpringTest-context_mapConfig_full.xml", "classpath:/spring/test_eaaf_core.beans.xml"}) +//@TestPropertySource(locations = { "classpath:/config/junit_config_1_springboot.properties" }) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test1.xml", + "/SpringTest-context_basic_mapConfig1.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 DummyAuthConfigMap 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("modules.idaustriaclient.request.sign.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); + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, null); + // oaParam.setMandateProfilesCsv( + // RandomStringUtils.randomAlphabetic(5) + // + "," + RandomStringUtils.randomAlphabetic(5) + // + "," + RandomStringUtils.randomAlphabetic(5)); + + 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.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_NODE_ENTITYID, + RandomStringUtils.randomAlphabetic(10)); + + try { + task.execute(pendingReq, executionContext); + Assert.fail(); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, + e.getOriginalException()); + Assert.assertEquals("module.eidasauth.02", + ((EaafConfigurationException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void noMetadataAvailableOnSpConfig() { + oaParam.putGenericConfigurationKey(IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, + RandomStringUtils.randomAlphabetic(10)); + + try { + task.execute(pendingReq, executionContext); + Assert.fail(); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, + e.getOriginalException()); + Assert.assertEquals("module.eidasauth.02", + ((EaafConfigurationException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void noMetadataSigningKeyStore() throws Pvp2MetadataException { + oaParam.putGenericConfigurationKey(IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, + METADATA_PATH); + + authConfig.removeConfigValue("modules.idaustriaclient.request.sign.alias"); + + metadataProvider.addMetadataResolverIntoChain( + metadataFactory.createMetadataProvider(METADATA_PATH, null, "jUnitTest", null)); + + try { + task.execute(pendingReq, executionContext); + Assert.fail(); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(CredentialsNotAvailableException.class, + e.getOriginalException()); + Assert.assertEquals("internal.pvp.01", + ((CredentialsNotAvailableException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void success() throws Exception { + oaParam.putGenericConfigurationKey(IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, + METADATA_PATH); + metadataProvider.addMetadataResolverIntoChain( + metadataFactory.createMetadataProvider(METADATA_PATH, null, "jUnitTest", null)); + pendingReq.setTransactionId(RandomStringUtils.randomAlphanumeric(10)); + + task.execute(pendingReq, executionContext); + + final EaafRequestedAttributes reqAttr = validate(); + Assert.assertEquals("#Req Attribute", 2, reqAttr.getAttributes().size()); + + Assert.assertEquals("Wrong req attr.", "urn:eidgvat:attributes.transactionId", + reqAttr.getAttributes().get(0).getName()); + Assert.assertNotNull("Req. Attr value element", reqAttr.getAttributes().get(0).getAttributeValues()); + Assert.assertEquals("#Req. Attr value", 1, + reqAttr.getAttributes().get(0).getAttributeValues().size()); + org.springframework.util.Assert.isInstanceOf(XSString.class, + reqAttr.getAttributes().get(0).getAttributeValues().get(0), "Wrong requested Attributes Value type"); + Assert.assertEquals("Req. Attr. Value", pendingReq.getUniqueTransactionIdentifier(), + ((XSString) reqAttr.getAttributes().get(0).getAttributeValues().get(0)).getValue()); + + Assert.assertEquals("Wrong req attr.", "urn:oid:1.2.40.0.10.2.1.1.261.34", + reqAttr.getAttributes().get(1).getName()); + Assert.assertNotNull("Req. Attr value element", reqAttr.getAttributes().get(1).getAttributeValues()); + Assert.assertEquals("#Req. Attr value", 1, + reqAttr.getAttributes().get(1).getAttributeValues().size()); + org.springframework.util.Assert.isInstanceOf(XSString.class, + reqAttr.getAttributes().get(1).getAttributeValues().get(0), "Wrong requested Attributes Value type"); + Assert.assertEquals("Req. Attr. Value", oaParam.getAreaSpecificTargetIdentifier(), + ((XSString) reqAttr.getAttributes().get(1).getAttributeValues().get(0)).getValue()); + + } + + private EaafRequestedAttributes validate() throws Exception { + Assert.assertEquals("HTTP Statuscode", 200, httpResp.getStatus()); + Assert.assertEquals("ContentType", "text/html;charset=UTF-8", httpResp.getContentType()); + Assert.assertEquals("ContentEncoding", "UTF-8", httpResp.getCharacterEncoding()); + + final String html = httpResp.getContentAsString(); + Assert.assertNotNull("XML Metadata", html); + + final int startIndex = html.indexOf("SAMLRequest="); + Assert.assertTrue("No SAMLRequest in html", startIndex >= 0); + final String authnXml = html.substring(startIndex + "SAMLRequest=".length()); + //TODO why do i have to do that?? => remove "} from end +// String authnXml2 = authnXml1.substring(0,authnXml1.length()-2); + + //check if relaystate was stored + final int startIndexRelayState = html.indexOf("RelayState="); + Assert.assertTrue("wrong RelayState in HTML", + startIndexRelayState >= 0); + String relayState = html.substring(startIndexRelayState + "RelayState=".length(), startIndex); +// String storedPendingReqId = transactionStorage.get(relayState, String.class); +// Assert.assertEquals("relayStore not map to pendingRequestId", +// pendingReq.getPendingRequestId(), storedPendingReqId); + + + final AuthnRequest authnRequest = (AuthnRequest) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), new ByteArrayInputStream( + Base64.getDecoder().decode(authnXml))); + + Assert.assertNotNull("AuthnReq", authnRequest); + Assert.assertNotNull("Issuer", authnRequest.getIssuer()); + Assert.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)); +//TODO + //check other elements +// Assert.assertNotNull("Proxy-Scope", authnRequest.getScoping()); +// Assert.assertNotNull("RequesterIds", authnRequest.getScoping().getRequesterIDs()); +// Assert.assertEquals("#RequesterIds", 1, authnRequest.getScoping().getRequesterIDs().size()); +// Assert.assertEquals("RequesterId", oaParam.getUniqueApplicationRegisterIdentifier(), +// authnRequest.getScoping().getRequesterIDs().get(0).getRequesterID()); + + Assert.assertNotNull("RequestedAuthnContext", authnRequest.getRequestedAuthnContext()); + Assert.assertNotNull("AuthnContextClassRef", + authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs()); + Assert.assertEquals("#AuthnContextClassRef", 1, + authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().size()); + Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/high", + authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef()); + + Assert.assertNotNull("Extensions", authnRequest.getExtensions()); + Assert.assertFalse("No Requested attributes", + authnRequest.getExtensions().getUnknownXMLObjects().isEmpty()); + + Assert.assertEquals("#ReqAttributes", 1, authnRequest.getExtensions().getUnknownXMLObjects().size()); + org.springframework.util.Assert.isInstanceOf(EaafRequestedAttributes.class, + authnRequest.getExtensions().getUnknownXMLObjects().get(0), "No Requested Attributes object"); + + return (EaafRequestedAttributes) authnRequest.getExtensions().getUnknownXMLObjects().get(0); + } + + private IVelocityGuiBuilderConfiguration createDummyGuiConfig() { + return new IVelocityGuiBuilderConfiguration() { + + @Override + public Map 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; + + } + }; + } + +} -- cgit v1.2.3 From effa0dc13b11d18ef917dcd1f8be3a21d686b735 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Mon, 8 Feb 2021 15:09:46 +0100 Subject: added ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest --- .../eidas/v2/test/dummy/DummyPendingRequest.java | 8 + ...enerateMobilePhoneSignatureRequestTaskTest.java | 8 +- ...natureResponseAndSearchInRegistersTaskTest.java | 775 +++++++++++++++++++++ 3 files changed, 788 insertions(+), 3 deletions(-) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/dummy/DummyPendingRequest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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/tasks/GenerateMobilePhoneSignatureRequestTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateMobilePhoneSignatureRequestTaskTest.java index 379f64ee..2579bb40 100644 --- 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 @@ -22,6 +22,8 @@ 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.apache.commons.lang3.StringUtils; import org.junit.Assert; @@ -73,8 +75,8 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { private PvpMetadataResolverFactory metadataFactory; @Autowired private DummyGuiBuilderConfigurationFactory guiBuilderConfigFactory; -// @Autowired -// private SamlVerificationEngine samlVerifyEngine; + @Autowired + private SamlVerificationEngine samlVerifyEngine; // @Autowired // private ITransactionStorage transactionStorage; @@ -284,7 +286,7 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { msg.setEntityID(authnRequest.getIssuer().getValue()); metadataProvider.addMetadataResolverIntoChain( metadataFactory.createMetadataProvider(METADATA_SP_PATH, null, "jUnit SP", null)); -// samlVerifyEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); + //samlVerifyEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); //TODO //check other elements // Assert.assertNotNull("Proxy-Scope", authnRequest.getScoping()); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java new file mode 100644 index 00000000..a07343f9 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java @@ -0,0 +1,775 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + + +import java.io.IOException; +import java.util.Base64; + +import javax.xml.transform.TransformerException; + +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthCredentialProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthMetadataProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyAuthConfigMap; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyPendingRequest; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.io.UnmarshallingException; +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.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 at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; +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.process.ExecutionContextImpl; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.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.sp.exception.AuthnResponseValidationException; +import net.shibboleth.utilities.java.support.xml.XMLParserException; + +@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration({"/spring/SpringTest-context_mapConfig_full.xml", "classpath:/spring/test_eaaf_core.beans.xml"}) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test1.xml", + "/SpringTest-context_basic_mapConfig1.xml" +}) +public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { + + private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; + private static final String TEST_SIGNED_AUTHBLOCK = "MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQG" + + "EwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMw" + + "MDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0" + + "YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SYO4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eT" + + "OWdiQX0GpDIBspYMZh8ZKcwwCgYIKoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImnAiA2KwFt" + + "zO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA=="; + + @Autowired(required = true) + private ApplicationContext context; + @Autowired(required = true) + protected DummyAuthConfigMap authConfig; + @Autowired private IdAustriaClientAuthMetadataProvider metadataProvider; + @Autowired private IdAustriaClientAuthCredentialProvider credentialProvider; + @Autowired private PvpMetadataResolverFactory metadataFactory; + + final ExecutionContext executionContext = new ExecutionContextImpl(); + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private DummyPendingRequest pendingReq; + private DummyOA oaParam; + + private ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask 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 = (ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask) context.getBean("ReceiveMobilePhoneSignatureResponseTask"); + + 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("modules.eidascentralauth.request.sign.alias", "sig"); +// authConfig.putConfigValue(AuthHandlerConstants.PROP_CONFIG_LEGACY_ALLOW, "false"); + + oaParam = new DummyOA(); + oaParam.setUniqueAppId("http://test.com/test"); + oaParam.setTargetIdentifier( + EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); + oaParam.setEidasEnabled(true); + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, null); + oaParam.setMandateProfilesCsv( + RandomStringUtils.randomAlphabetic(5) + + "," + RandomStringUtils.randomAlphabetic(5) + + "," + RandomStringUtils.randomAlphabetic(5)); + + pendingReq = new DummyPendingRequest(); + pendingReq.initialize(httpReq, authConfig); + pendingReq.setPendingRequestId(RandomStringUtils.randomAlphanumeric(10)); + pendingReq.setOnlineApplicationConfiguration(oaParam); + //pendingReq.setAuthUrl("https://localhost/authhandler"); + + metadataProvider.fullyDestroy(); + + } + + @Test + public void unsupportedHttpMethode() { + httpReq = new MockHttpServletRequest("PUT", "https://localhost/authhandler"); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.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)); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostNoMessage() { + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostMessageNotSigned() throws IOException { + + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + IOUtils.toByteArray(ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.class.getResourceAsStream( + "/data/Response_without_sig_classpath_entityid.xml")))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostMessageWrongDestinationEndpoint() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + TransformerException, MarshallingException { + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_with_wrong_destination_endpoint.xml", + credentialProvider.getMessageSigningCredential(), true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedNoMetadata() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_classpath_entityid.xml", + credentialProvider.getMessageSigningCredential(), true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.11", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedAssertionOutDated() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_classpath_entityid.xml", + credentialProvider.getMessageSigningCredential(), false); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedAssertionFromWrongIdp() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, "http://wrong.idp"); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_classpath_entityid.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.08", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedAssertionMissingAttributes() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_classpath_entityid.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedWithError() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_with_error.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.05", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedWitUserStopErrorCode() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException, TaskExecutionException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_with_error_userstop.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + //perform test + task.execute(pendingReq, executionContext); + + //validate state + Assert.assertTrue("process not cancelled", executionContext.isProcessCancelled()); + Assert.assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); + Assert.assertFalse("should not authenticated", pendingReq.isAuthenticated()); + + } + + @Test + public void httpPostValidSignedWithErrorAndNoSubCode() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_with_error_without_subcode.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.05", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedWithErrorAndEmptySubCode() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_without_sig_with_error_empty_subcode.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.05", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void responseWrongEidasBind() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_with_EID_wrong_data.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void httpPostValidSignedAssertionEidValid() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException, TaskExecutionException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_with_EID.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + //perform task + task.execute(pendingReq, executionContext); + + //validate state +// Assert.assertTrue("Wrong EID-Process flag", +// (boolean) executionContext.get(AuthHandlerConstants.PROCESSCONTEXT_WAS_EID_PROCESS)); +// Assert.assertFalse("Wrong Mandate flag", +// (boolean) executionContext.get(AuthHandlerConstants.HTTP_PARAM_USE_MANDATES)); + + Assert.assertEquals("piiTransactionId", "piiId_112233445566", pendingReq.getUniquePiiTransactionIdentifier()); + + final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); + + Assert.assertTrue("E-ID flag", session.isEidProcess()); + Assert.assertTrue("Foreign flag", session.isForeigner()); +// Assert.assertEquals("eidasBind", EIDAS_BIND, session.getQcBind()); +// Assert.assertEquals("vsz", +// "OD/kCGIFbjLTW0po6IZSmoaz3uhPYlO3S5bs9JnK0A5DHtufM3APLuDc3Llp4PeNdEa4NrCmgHr1YUiHT5irT8eDAfGpIbQHJg==", +// session.getVsz()); +// Assert.assertArrayEquals("signedConsent", +// Base64.getDecoder().decode(TEST_SIGNED_AUTHBLOCK), session.getSignedAuthBlock()); +// Assert.assertEquals("AuthBlockType", AuthHandlerConstants.AuthBlockType.JWS, session.getSignedAuthBlockType()); + + Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); + Assert.assertEquals("CountryCode", "IT", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); + Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); + +// Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); + +// Assert.assertFalse("Mandate flag", session.isMandateUsed()); +// Assert.assertNull("MandateInfos", session.getMandateDate()); + + Assert.assertNull("MandateType", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_TYPE_NAME, String.class)); + Assert.assertNull("Legal Person CommonName", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_FULL_NAME_NAME, String.class)); + Assert.assertNull("Legal Person SourcePin",session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_NAME, String.class)); + Assert.assertNull("Legal Person SourcePinType", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class)); + } + + @Test + public void httpPostValidSignedAssertionLegacyValid() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException, TaskExecutionException { +// authConfig.putConfigValue(AuthHandlerConstants.PROP_CONFIG_LEGACY_ALLOW, "true"); + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_with_legacy.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + String piiTransId = pendingReq.getUniquePiiTransactionIdentifier(); + + //perform task + task.execute(pendingReq, executionContext); + + //validate state +// Assert.assertFalse("Wrong EID-Process flag", +// (boolean) executionContext.get(AuthHandlerConstants.PROCESSCONTEXT_WAS_EID_PROCESS)); +// Assert.assertFalse("Wrong Mandate flag", +// (boolean) executionContext.get(AuthHandlerConstants.HTTP_PARAM_USE_MANDATES)); + + Assert.assertEquals("piiTransactionId", piiTransId, pendingReq.getUniquePiiTransactionIdentifier()); + + final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); + + Assert.assertFalse("E-ID flag", session.isEidProcess()); + Assert.assertTrue("Foreign flag", session.isForeigner()); + Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/test", session.getQaaLevel()); + Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); + Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); + + Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); + Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); + Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); + + Assert.assertEquals("bPK", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); + Assert.assertEquals("bPK-Target", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); + Assert.assertEquals("AuthBlock", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); + +// Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); +// Assert.assertNull("eidasBind", session.getQcBind()); +// Assert.assertNull("signedConsent", session.getSignedAuthBlock()); +// Assert.assertEquals("signedConsentType", AuthBlockType.NONE, session.getSignedAuthBlockType()); + + Assert.assertFalse("Mandate flag", session.isMandateUsed()); +// Assert.assertNull("MandateInfos", session.getMandateDate()); + + } + + @Test + public void httpPostValidSignedAssertionWithLegacyAndEid() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException, TaskExecutionException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_with_legacy_and_EID.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + //perform task + task.execute(pendingReq, executionContext); + + //validate state +// Assert.assertTrue("Wrong EID-Process flag", +// (boolean) executionContext.get(AuthHandlerConstants.PROCESSCONTEXT_WAS_EID_PROCESS)); + final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); +// Assert.assertFalse("Wrong Mandate flag", +// (boolean) executionContext.get(AuthHandlerConstants.HTTP_PARAM_USE_MANDATES)); + +// Assert.assertTrue("E-ID flag", session.isEidProcess()); +// Assert.assertTrue("Foreign flag", session.isForeigner()); + Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/test", session.getQaaLevel()); + Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); + Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); + +// Assert.assertEquals("eidasBind", EIDAS_BIND, session.getQcBind()); +// Assert.assertArrayEquals("signedConsent", +// Base64.getDecoder().decode(TEST_SIGNED_AUTHBLOCK), session.getSignedAuthBlock()); + + Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); + Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); + Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); + + Assert.assertEquals("FamilyName", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); + Assert.assertEquals("FamilyName", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); + Assert.assertEquals("FamilyName", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); + +// Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); + + Assert.assertFalse("Mandate flag", session.isMandateUsed()); +// Assert.assertNull("MandateInfos", session.getMandateDate()); + + Assert.assertNull("MandateType", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_TYPE_NAME, String.class)); + Assert.assertNull("Legal Person CommonName", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_FULL_NAME_NAME, String.class)); + Assert.assertNull("Legal Person SourcePin",session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_NAME, String.class)); + Assert.assertNull("Legal Person SourcePinType", session.getGenericDataFromSession( + ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class)); + + } + + + + + private Response initializeResponse(String idpEntityId, String responsePath, EaafX509Credential credential, + boolean validConditions) throws SamlSigningException, XMLParserException, UnmarshallingException, + Pvp2MetadataException { + + final Response response = (Response) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.class.getResourceAsStream(responsePath)); + response.setIssueInstant(DateTime.now()); + final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class); + issuer.setValue(idpEntityId); + response.setIssuer(issuer); + + if (validConditions) { + response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5)); + + } + + return Saml2Utils.signSamlObject(response, credential, true); + } + +} -- cgit v1.2.3 From cfb4a314b65e4c0af5cb1be297e131155a2571c9 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Tue, 9 Feb 2021 21:09:48 +0100 Subject: extract qaa & IssueInstant --- ...natureResponseAndSearchInRegistersTaskTest.java | 109 +++++++-------------- 1 file changed, 37 insertions(+), 72 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java index a07343f9..2e3da7bc 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java @@ -325,7 +325,7 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { METADATA_PATH, null, "jUnit IDP", null)); final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", + "classpath:/data/idp_metadata_classpath_entity.xml1", "/data/Response_without_sig_classpath_entityid.xml", credentialProvider.getMessageSigningCredential(), true); @@ -517,41 +517,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { } } - @Test - public void responseWrongEidasBind() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_EID_wrong_data.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); - - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((EaafException) e.getOriginalException()).getErrorId()); - - } - } - @Test public void httpPostValidSignedAssertionEidValid() throws IOException, SamlSigningException, Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, @@ -580,12 +545,12 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { // Assert.assertFalse("Wrong Mandate flag", // (boolean) executionContext.get(AuthHandlerConstants.HTTP_PARAM_USE_MANDATES)); - Assert.assertEquals("piiTransactionId", "piiId_112233445566", pendingReq.getUniquePiiTransactionIdentifier()); +// Assert.assertEquals("piiTransactionId", "piiId_112233445566", pendingReq.getUniquePiiTransactionIdentifier()); final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); - Assert.assertTrue("E-ID flag", session.isEidProcess()); - Assert.assertTrue("Foreign flag", session.isForeigner()); +// Assert.assertTrue("E-ID flag", session.isEidProcess()); +// Assert.assertTrue("Foreign flag", session.isForeigner()); // Assert.assertEquals("eidasBind", EIDAS_BIND, session.getQcBind()); // Assert.assertEquals("vsz", // "OD/kCGIFbjLTW0po6IZSmoaz3uhPYlO3S5bs9JnK0A5DHtufM3APLuDc3Llp4PeNdEa4NrCmgHr1YUiHT5irT8eDAfGpIbQHJg==", @@ -595,8 +560,8 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { // Assert.assertEquals("AuthBlockType", AuthHandlerConstants.AuthBlockType.JWS, session.getSignedAuthBlockType()); Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); - Assert.assertEquals("CountryCode", "IT", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); +// Assert.assertEquals("CountryCode", "IT", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); // Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); @@ -649,25 +614,25 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); Assert.assertFalse("E-ID flag", session.isEidProcess()); - Assert.assertTrue("Foreign flag", session.isForeigner()); +// Assert.assertTrue("Foreign flag", session.isForeigner()); Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/test", session.getQaaLevel()); - Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); +// Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); - Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); - Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); - Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); - - Assert.assertEquals("bPK", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); - Assert.assertEquals("bPK-Target", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); - Assert.assertEquals("AuthBlock", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); +// Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); +// Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); +// Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); +// +// Assert.assertEquals("bPK", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); +// Assert.assertEquals("bPK-Target", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); +// Assert.assertEquals("AuthBlock", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); // Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); // Assert.assertNull("eidasBind", session.getQcBind()); @@ -711,27 +676,27 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { // Assert.assertTrue("E-ID flag", session.isEidProcess()); // Assert.assertTrue("Foreign flag", session.isForeigner()); Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/test", session.getQaaLevel()); - Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); +// Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); // Assert.assertEquals("eidasBind", EIDAS_BIND, session.getQcBind()); // Assert.assertArrayEquals("signedConsent", // Base64.getDecoder().decode(TEST_SIGNED_AUTHBLOCK), session.getSignedAuthBlock()); - Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); - Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); - Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); - - Assert.assertEquals("FamilyName", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); - Assert.assertEquals("FamilyName", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); - Assert.assertEquals("FamilyName", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); +// Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); +// Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); +// Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); +// +// Assert.assertEquals("FamilyName", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); +// Assert.assertEquals("FamilyName", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); +// Assert.assertEquals("FamilyName", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( +// ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); // Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); -- cgit v1.2.3 From f681c2e66c4913a37505788b270e70b85ed1111e Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 12 Feb 2021 11:08:57 +0100 Subject: compare eiddata with mobile phone signature data --- ...natureResponseAndSearchInRegistersTaskTest.java | 78 +++++++++++++++++++++- 1 file changed, 75 insertions(+), 3 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java index 2e3da7bc..fbf011b1 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java @@ -6,6 +6,10 @@ import java.util.Base64; import javax.xml.transform.TransformerException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthCredentialProvider; import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthMetadataProvider; @@ -13,6 +17,7 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveMobilePhone import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyAuthConfigMap; import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyPendingRequest; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomStringUtils; @@ -520,7 +525,7 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { @Test public void httpPostValidSignedAssertionEidValid() throws IOException, SamlSigningException, Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException { + MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { oaParam.putGenericConfigurationKey( IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); @@ -536,6 +541,14 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + //put SimpleEidasData in session + final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = new SimpleEidasData(); + eidData.setFamilyName("Mustermann"); + eidData.setGivenName("Max"); + eidData.setDateOfBirth("1940-01-01"); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + //perform task task.execute(pendingReq, executionContext); @@ -579,10 +592,53 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class)); } + @Test + public void httpPostValidSignedAssertionEidValidButNameMissmatch() throws IOException, SamlSigningException, + Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, + MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { + + oaParam.putGenericConfigurationKey( + IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); + + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + + final Response response = initializeResponse( + "classpath:/data/idp_metadata_classpath_entity.xml", + "/data/Response_with_EID.xml", + credentialProvider.getMessageSigningCredential(), + true); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + + //put SimpleEidasData in session + final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = new SimpleEidasData(); + eidData.setFamilyName("Mustermann1"); + eidData.setGivenName("Max"); + eidData.setDateOfBirth("1940-01-01"); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + + //perform task + try { + task.execute(pendingReq, executionContext); + Assert.fail("Invalid response not detected"); + + } catch (final TaskExecutionException e) { + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertTrue(e.getOriginalException().getCause() instanceof InvalidUserInputException); + } + + } + @Test public void httpPostValidSignedAssertionLegacyValid() throws IOException, SamlSigningException, Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException { + MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { // authConfig.putConfigValue(AuthHandlerConstants.PROP_CONFIG_LEGACY_ALLOW, "true"); oaParam.putGenericConfigurationKey( IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); @@ -590,6 +646,14 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); + //put SimpleEidasData in session + final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = new SimpleEidasData(); + eidData.setFamilyName("Mustermann"); + eidData.setGivenName("Max"); + eidData.setDateOfBirth("1940-01-01"); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + final Response response = initializeResponse( "classpath:/data/idp_metadata_classpath_entity.xml", "/data/Response_with_legacy.xml", @@ -647,7 +711,7 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { @Test public void httpPostValidSignedAssertionWithLegacyAndEid() throws IOException, SamlSigningException, Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException { + MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { oaParam.putGenericConfigurationKey( IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); @@ -655,6 +719,14 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); + //put SimpleEidasData in session + final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = new SimpleEidasData(); + eidData.setFamilyName("Mustermann"); + eidData.setGivenName("Max"); + eidData.setDateOfBirth("1940-01-01"); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + final Response response = initializeResponse( "classpath:/data/idp_metadata_classpath_entity.xml", "/data/Response_with_legacy_and_EID.xml", -- cgit v1.2.3 From eeecdd8e6063298bb6414b9f6a8b0bc4cee2eba4 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Fri, 12 Feb 2021 14:31:04 +0100 Subject: tests working, added IdAustriaClientAuthSignalController --- ...eiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java index fbf011b1..550c2f13 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java @@ -68,6 +68,7 @@ import net.shibboleth.utilities.java.support.xml.XMLParserException; public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; + private static final String METADATA_PATH1 = "classpath:/data/idp_metadata_classpath_entity1.xml"; private static final String TEST_SIGNED_AUTHBLOCK = "MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQG" + "EwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMw" + "MDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0" @@ -328,9 +329,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH1, null, "jUnit IDP", null)); final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml1", + "classpath:/data/idp_metadata_classpath_entity1.xml", "/data/Response_without_sig_classpath_entityid.xml", credentialProvider.getMessageSigningCredential(), true); -- cgit v1.2.3 From 6017e30de786ab9defab7eaef53ec8da5f606ee9 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Fri, 19 Feb 2021 16:14:31 +0100 Subject: refactoring of ID Austria connection client and add/update of jUnit tests --- .../config/EidasConnectorMessageSourceTest.java | 43 ++ .../IdAustriaAuthSignalControllerTest.java | 197 +++++++ .../IdAustriaClientAuthHealthCheckTest.java | 128 +++++ .../IdAustriaClientAuthMetadataControllerTest.java | 44 +- ...AustriaClientAuthMetadataProviderFirstTest.java | 238 +++++++++ ...ustriaClientAuthMetadataProviderSecondTest.java | 66 +++ .../IdAustriaClientCredentialProviderTest.java | 414 +++++++++++++++ ...enerateMobilePhoneSignatureRequestTaskTest.java | 245 ++++----- ...natureResponseAndSearchInRegistersTaskTest.java | 564 ++++++--------------- 9 files changed, 1342 insertions(+), 597 deletions(-) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/config/EidasConnectorMessageSourceTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaAuthSignalControllerTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthHealthCheckTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderFirstTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientAuthMetadataProviderSecondTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/idaustriaclient/IdAustriaClientCredentialProviderTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 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/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 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 index c99c6e6a..4671684f 100644 --- 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 @@ -3,18 +3,10 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.idaustriaclient; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthCredentialProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthMetadataController; -import at.gv.egiz.eaaf.core.test.dummy.DummyAuthConfigMap; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; @@ -24,16 +16,16 @@ 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.opensaml.security.x509.BasicX509Credential; 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.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import at.gv.egiz.eaaf.core.api.data.PvpAttributeDefinitions; +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; @@ -43,14 +35,11 @@ import net.shibboleth.utilities.java.support.xml.XMLParserException; @RunWith(SpringJUnit4ClassRunner.class) -//@TestPropertySource(locations = {"classpath:/config/junit_config_de_attributes.properties"}) -@TestPropertySource(locations = { "classpath:/config/junit_config_1_springboot.properties" }) @ContextConfiguration(locations = { "/SpringTest-context_tasks_test.xml", "/SpringTest-context_basic_mapConfig.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -@Ignore public class IdAustriaClientAuthMetadataControllerTest { private MockHttpServletRequest httpReq; @@ -58,7 +47,6 @@ public class IdAustriaClientAuthMetadataControllerTest { @Autowired private IdAustriaClientAuthMetadataController controller; @Autowired private IdAustriaClientAuthCredentialProvider credProvider; - @Autowired private DummyAuthConfigMap config; /** * JUnit class initializer. @@ -80,28 +68,17 @@ public class IdAustriaClientAuthMetadataControllerTest { httpReq.setContextPath("/authhandler"); httpResp = new MockHttpServletResponse(); - config.removeConfigValue("core.legacy.allowLegacyMode"); - config.removeConfigValue("modules.eidascentralauth.semper.mandates.active"); - config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.1"); - config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.2"); - config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.3"); - config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.4"); - config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.5"); - config.removeConfigValue("modules.eidascentralauth.required.additional.attributes.6"); - } @Test public void buildMetadataValidInEidMode() throws IOException, EaafException, XMLParserException, UnmarshallingException, FilterException { - config.putConfigValue("core.legacy.allowLegacyMode", "false"); - config.putConfigValue("modules.eidascentralauth.semper.mandates.active", "false"); //build metdata controller.getSpMetadata(httpReq, httpResp); //check result - validateResponse(6); + validateResponse(7); } @@ -137,10 +114,6 @@ public class IdAustriaClientAuthMetadataControllerTest { Assert.assertFalse("AssertionConsumerServices", spSsoDesc.getAssertionConsumerServices().isEmpty()); - Assert.assertFalse("ContactPersons", - metadata.getContactPersons().isEmpty()); - Assert.assertNotNull("ContactPersons", - metadata.getOrganization()); Assert.assertFalse("KeyDescriptors", spSsoDesc.getKeyDescriptors().isEmpty()); @@ -157,13 +130,4 @@ public class IdAustriaClientAuthMetadataControllerTest { spSsoDesc.getAttributeConsumingServices().get(0).getRequestAttributes().size()); } - - private List convertX509Certs(List certs) { - final List result = new ArrayList<>(); - for (final X509Certificate cert : certs) { - result.add(new BasicX509Credential(cert)); - - } - return result; - } } 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 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 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/GenerateMobilePhoneSignatureRequestTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateMobilePhoneSignatureRequestTaskTest.java index 2579bb40..4fb05a35 100644 --- 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 @@ -1,38 +1,19 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthMetadataProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.GenerateMobilePhoneSignatureRequestTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyAuthConfigMap; -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.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.api.reqattr.EaafRequestedAttribute; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes; -import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; -import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2InternalErrorException; -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 static org.junit.Assert.assertThrows; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Base64; +import java.util.Map; + import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; 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.schema.XSString; import org.opensaml.core.xml.util.XMLObjectSupport; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.saml2.core.AuthnRequest; @@ -41,23 +22,38 @@ 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.TestPropertySource; 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 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; @RunWith(SpringJUnit4ClassRunner.class) -@TestPropertySource(locations = {"classpath:/config/junit_config_1-.properties" }) -//@ContextConfiguration({"/spring/SpringTest-context_mapConfig_full.xml", "classpath:/spring/test_eaaf_core.beans.xml"}) -//@TestPropertySource(locations = { "classpath:/config/junit_config_1_springboot.properties" }) @ContextConfiguration(locations = { - "/SpringTest-context_tasks_test1.xml", - "/SpringTest-context_basic_mapConfig1.xml" + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml", + "classpath:/eaaf_pvp_sp.beans.xml" }) public class GenerateMobilePhoneSignatureRequestTaskTest { @@ -68,7 +64,7 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { @Autowired(required = true) private ApplicationContext context; @Autowired(required = true) - protected DummyAuthConfigMap authConfig; + protected MsConnectorDummyConfigMap authConfig; @Autowired private IdAustriaClientAuthMetadataProvider metadataProvider; @Autowired @@ -77,8 +73,8 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { private DummyGuiBuilderConfigurationFactory guiBuilderConfigFactory; @Autowired private SamlVerificationEngine samlVerifyEngine; -// @Autowired -// private ITransactionStorage transactionStorage; + @Autowired + private ITransactionStorage transactionStorage; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -106,27 +102,26 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { */ @Before public void setUp() throws Exception { - task = (GenerateMobilePhoneSignatureRequestTask) context.getBean("GenerateMobilePhoneSignatureRequestTask"); + 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("modules.idaustriaclient.request.sign.alias", "sig"); + 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.setBmiUniqueIdentifier(oaParam.getUniqueIdentifier() + "#" + RandomStringUtils.randomAlphanumeric( + 5)); oaParam.setTargetIdentifier( EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); oaParam.setEidasEnabled(true); - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, null); - // oaParam.setMandateProfilesCsv( - // RandomStringUtils.randomAlphabetic(5) - // + "," + RandomStringUtils.randomAlphabetic(5) - // + "," + RandomStringUtils.randomAlphabetic(5)); pendingReq = new TestRequestImpl(); pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); @@ -140,108 +135,69 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { @Test public void noMetadataAvailableOnGlobalConfig() { - authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_NODE_ENTITYID, - RandomStringUtils.randomAlphabetic(10)); - - try { - task.execute(pendingReq, executionContext); - Assert.fail(); - - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, - e.getOriginalException()); - Assert.assertEquals("module.eidasauth.02", - ((EaafConfigurationException) e.getOriginalException()).getErrorId()); - - } + authConfig.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID); + + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, + e.getOriginalException()); + Assert.assertEquals("module.eidasauth.00", + ((EaafConfigurationException) e.getOriginalException()).getErrorId()); + } @Test - public void noMetadataAvailableOnSpConfig() { - oaParam.putGenericConfigurationKey(IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, - RandomStringUtils.randomAlphabetic(10)); - - try { - task.execute(pendingReq, executionContext); - Assert.fail(); - - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, - e.getOriginalException()); - Assert.assertEquals("module.eidasauth.02", - ((EaafConfigurationException) e.getOriginalException()).getErrorId()); - - } + 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)); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, + e.getOriginalException()); + Assert.assertEquals("module.eidasauth.idaustria.02", + ((EaafConfigurationException) e.getOriginalException()).getErrorId()); + } @Test public void noMetadataSigningKeyStore() throws Pvp2MetadataException { - oaParam.putGenericConfigurationKey(IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, - METADATA_PATH); - - authConfig.removeConfigValue("modules.idaustriaclient.request.sign.alias"); + authConfig.removeConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS); metadataProvider.addMetadataResolverIntoChain( metadataFactory.createMetadataProvider(METADATA_PATH, null, "jUnitTest", null)); - try { - task.execute(pendingReq, executionContext); - Assert.fail(); - - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(CredentialsNotAvailableException.class, - e.getOriginalException()); - Assert.assertEquals("internal.pvp.01", - ((CredentialsNotAvailableException) e.getOriginalException()).getErrorId()); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(CredentialsNotAvailableException.class, + e.getOriginalException()); + Assert.assertEquals("internal.pvp.01", + ((CredentialsNotAvailableException) e.getOriginalException()).getErrorId()); - } } @Test public void success() throws Exception { - oaParam.putGenericConfigurationKey(IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, - METADATA_PATH); metadataProvider.addMetadataResolverIntoChain( metadataFactory.createMetadataProvider(METADATA_PATH, null, "jUnitTest", null)); pendingReq.setTransactionId(RandomStringUtils.randomAlphanumeric(10)); task.execute(pendingReq, executionContext); - final EaafRequestedAttributes reqAttr = validate(); - Assert.assertEquals("#Req Attribute", 2, reqAttr.getAttributes().size()); - - Assert.assertEquals("Wrong req attr.", "urn:eidgvat:attributes.transactionId", - reqAttr.getAttributes().get(0).getName()); - Assert.assertNotNull("Req. Attr value element", reqAttr.getAttributes().get(0).getAttributeValues()); - Assert.assertEquals("#Req. Attr value", 1, - reqAttr.getAttributes().get(0).getAttributeValues().size()); - org.springframework.util.Assert.isInstanceOf(XSString.class, - reqAttr.getAttributes().get(0).getAttributeValues().get(0), "Wrong requested Attributes Value type"); - Assert.assertEquals("Req. Attr. Value", pendingReq.getUniqueTransactionIdentifier(), - ((XSString) reqAttr.getAttributes().get(0).getAttributeValues().get(0)).getValue()); - - Assert.assertEquals("Wrong req attr.", "urn:oid:1.2.40.0.10.2.1.1.261.34", - reqAttr.getAttributes().get(1).getName()); - Assert.assertNotNull("Req. Attr value element", reqAttr.getAttributes().get(1).getAttributeValues()); - Assert.assertEquals("#Req. Attr value", 1, - reqAttr.getAttributes().get(1).getAttributeValues().size()); - org.springframework.util.Assert.isInstanceOf(XSString.class, - reqAttr.getAttributes().get(1).getAttributeValues().get(0), "Wrong requested Attributes Value type"); - Assert.assertEquals("Req. Attr. Value", oaParam.getAreaSpecificTargetIdentifier(), - ((XSString) reqAttr.getAttributes().get(1).getAttributeValues().get(0)).getValue()); + validate(); } - private EaafRequestedAttributes validate() throws Exception { + private void validate() throws Exception { Assert.assertEquals("HTTP Statuscode", 200, httpResp.getStatus()); Assert.assertEquals("ContentType", "text/html;charset=UTF-8", httpResp.getContentType()); Assert.assertEquals("ContentEncoding", "UTF-8", httpResp.getCharacterEncoding()); @@ -252,18 +208,15 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { final int startIndex = html.indexOf("SAMLRequest="); Assert.assertTrue("No SAMLRequest in html", startIndex >= 0); final String authnXml = html.substring(startIndex + "SAMLRequest=".length()); - //TODO why do i have to do that?? => remove "} from end -// String authnXml2 = authnXml1.substring(0,authnXml1.length()-2); - //check if relaystate was stored + // check if relaystate was stored final int startIndexRelayState = html.indexOf("RelayState="); Assert.assertTrue("wrong RelayState in HTML", startIndexRelayState >= 0); - String relayState = html.substring(startIndexRelayState + "RelayState=".length(), startIndex); -// String storedPendingReqId = transactionStorage.get(relayState, String.class); -// Assert.assertEquals("relayStore not map to pendingRequestId", -// pendingReq.getPendingRequestId(), storedPendingReqId); - + final String relayState = html.substring(startIndexRelayState + "RelayState=".length(), startIndex); + final String storedPendingReqId = transactionStorage.get(relayState, String.class); + Assert.assertEquals("relayStore not map to pendingRequestId", + pendingReq.getPendingRequestId(), storedPendingReqId); final AuthnRequest authnRequest = (AuthnRequest) XMLObjectSupport.unmarshallFromInputStream( XMLObjectProviderRegistrySupport.getParserPool(), new ByteArrayInputStream( @@ -275,25 +228,17 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { "https://localhost/authhandler" + IdAustriaClientAuthConstants.ENDPOINT_METADATA, authnRequest.getIssuer().getValue()); - //check XML scheme + // check XML scheme Saml2Utils.schemeValidation(authnRequest); - - //check signature + // 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)); -//TODO - //check other elements -// Assert.assertNotNull("Proxy-Scope", authnRequest.getScoping()); -// Assert.assertNotNull("RequesterIds", authnRequest.getScoping().getRequesterIDs()); -// Assert.assertEquals("#RequesterIds", 1, authnRequest.getScoping().getRequesterIDs().size()); -// Assert.assertEquals("RequesterId", oaParam.getUniqueApplicationRegisterIdentifier(), -// authnRequest.getScoping().getRequesterIDs().get(0).getRequesterID()); + samlVerifyEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); Assert.assertNotNull("RequestedAuthnContext", authnRequest.getRequestedAuthnContext()); Assert.assertNotNull("AuthnContextClassRef", @@ -303,15 +248,6 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/high", authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef()); - Assert.assertNotNull("Extensions", authnRequest.getExtensions()); - Assert.assertFalse("No Requested attributes", - authnRequest.getExtensions().getUnknownXMLObjects().isEmpty()); - - Assert.assertEquals("#ReqAttributes", 1, authnRequest.getExtensions().getUnknownXMLObjects().size()); - org.springframework.util.Assert.isInstanceOf(EaafRequestedAttributes.class, - authnRequest.getExtensions().getUnknownXMLObjects().get(0), "No Requested Attributes object"); - - return (EaafRequestedAttributes) authnRequest.getExtensions().getUnknownXMLObjects().get(0); } private IVelocityGuiBuilderConfiguration createDummyGuiConfig() { @@ -334,7 +270,8 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { @Override public InputStream getTemplate(String viewName) { - return GenerateMobilePhoneSignatureRequestTaskTest.class.getResourceAsStream("/data/pvp_postbinding_template.html"); + return GenerateMobilePhoneSignatureRequestTaskTest.class.getResourceAsStream( + "/data/pvp_postbinding_template.html"); } @Override diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java index 550c2f13..fb34a2dd 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java @@ -1,24 +1,12 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; +import static org.junit.Assert.assertThrows; import java.io.IOException; import java.util.Base64; import javax.xml.transform.TransformerException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthCredentialProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthMetadataProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyAuthConfigMap; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyPendingRequest; -import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomStringUtils; import org.joda.time.DateTime; @@ -42,11 +30,22 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyPendingRequest; import at.gv.egiz.eaaf.core.api.data.EaafConstants; -import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.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.api.credential.EaafX509Credential; @@ -60,29 +59,24 @@ import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnResponseValidationExceptio import net.shibboleth.utilities.java.support.xml.XMLParserException; @RunWith(SpringJUnit4ClassRunner.class) -//@ContextConfiguration({"/spring/SpringTest-context_mapConfig_full.xml", "classpath:/spring/test_eaaf_core.beans.xml"}) @ContextConfiguration(locations = { - "/SpringTest-context_tasks_test1.xml", - "/SpringTest-context_basic_mapConfig1.xml" + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" }) public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; - private static final String METADATA_PATH1 = "classpath:/data/idp_metadata_classpath_entity1.xml"; - private static final String TEST_SIGNED_AUTHBLOCK = "MIIBbjCCARSgAwIBAgIEXh7TNzAKBggqhkjOPQQDAjA/MQswCQYDVQQG" - + "EwJBVDENMAsGA1UECgwERUdJWjEOMAwGA1UECwwFalVuaXQxETAPBgNVBAMMCG1ldGFkYXRhMB4XDTIwMDExNTA4NTQxNVoXDTMw" - + "MDExNDA4NTQxNVowPzELMAkGA1UEBhMCQVQxDTALBgNVBAoMBEVHSVoxDjAMBgNVBAsMBWpVbml0MREwDwYDVQQDDAhtZXRhZGF0" - + "YTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABBdBkaxt31p++aZeP3SmlWITj9SYO4McV2ccXFsH4X4QMHuKAMUvjxPm1kdU01eT" - + "OWdiQX0GpDIBspYMZh8ZKcwwCgYIKoZIzj0EAwIDSAAwRQIhAJ3QKlk9cd90s+i8y62fvmGF6LtfNO+JvkWqDUBeQImnAiA2KwFt" - + "zO7STAp9MEwQGe0vt0F8mO1ttrLE+rr6YxdwGA=="; @Autowired(required = true) private ApplicationContext context; @Autowired(required = true) - protected DummyAuthConfigMap authConfig; - @Autowired private IdAustriaClientAuthMetadataProvider metadataProvider; - @Autowired private IdAustriaClientAuthCredentialProvider credentialProvider; - @Autowired private PvpMetadataResolverFactory metadataFactory; + protected MsConnectorDummyConfigMap authConfig; + @Autowired + private IdAustriaClientAuthMetadataProvider metadataProvider; + @Autowired + private IdAustriaClientAuthCredentialProvider credentialProvider; + @Autowired + private PvpMetadataResolverFactory metadataFactory; final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -110,7 +104,8 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { */ @Before public void setUp() throws Exception { - task = (ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask) context.getBean("ReceiveMobilePhoneSignatureResponseTask"); + task = (ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask) context.getBean( + "ReceiveMobilePhoneSignatureResponseTask"); httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); httpReq.setScheme("https"); @@ -120,28 +115,18 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - authConfig.putConfigValue("modules.eidascentralauth.request.sign.alias", "sig"); -// authConfig.putConfigValue(AuthHandlerConstants.PROP_CONFIG_LEGACY_ALLOW, "false"); + authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, + METADATA_PATH); oaParam = new DummyOA(); oaParam.setUniqueAppId("http://test.com/test"); oaParam.setTargetIdentifier( EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); - oaParam.setEidasEnabled(true); - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, null); - oaParam.setMandateProfilesCsv( - RandomStringUtils.randomAlphabetic(5) - + "," + RandomStringUtils.randomAlphabetic(5) - + "," + RandomStringUtils.randomAlphabetic(5)); pendingReq = new DummyPendingRequest(); pendingReq.initialize(httpReq, authConfig); pendingReq.setPendingRequestId(RandomStringUtils.randomAlphanumeric(10)); pendingReq.setOnlineApplicationConfiguration(oaParam); - //pendingReq.setAuthUrl("https://localhost/authhandler"); metadataProvider.fullyDestroy(); @@ -153,20 +138,17 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.03", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.03", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } } @Test @@ -175,61 +157,52 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } } @Test public void httpPostNoMessage() { - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } } @Test public void httpPostMessageNotSigned() throws IOException { httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - IOUtils.toByteArray(ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.class.getResourceAsStream( - "/data/Response_without_sig_classpath_entityid.xml")))); - - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + IOUtils.toByteArray(ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.class + .getResourceAsStream( + "/data/Response_without_sig_classpath_entityid.xml")))); + + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - - } } @Test @@ -242,22 +215,20 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { "/data/Response_with_wrong_destination_endpoint.xml", credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } } @Test @@ -270,22 +241,19 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { "/data/Response_without_sig_classpath_entityid.xml", credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); + + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.11", + ((EaafException) e.getOriginalException()).getErrorId()); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.11", - ((EaafException) e.getOriginalException()).getErrorId()); - - } } @Test @@ -301,22 +269,20 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { "/data/Response_without_sig_classpath_entityid.xml", credentialProvider.getMessageSigningCredential(), false); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((EaafException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((EaafException) e.getOriginalException()).getErrorId()); - } } @Test @@ -324,36 +290,32 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, "http://wrong.idp"); - + authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, + "http://wrong.idp/" + RandomStringUtils.randomAlphabetic(5)); + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH1, null, "jUnit IDP", null)); final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity1.xml", + "classpath:/data/idp_metadata_classpath_entity.xml", "/data/Response_without_sig_classpath_entityid.xml", credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.08", - ((EaafException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.08", + ((EaafException) e.getOriginalException()).getErrorId()); - } } @Test @@ -361,9 +323,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -373,22 +332,20 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((EaafException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.12", + ((EaafException) e.getOriginalException()).getErrorId()); - } } @Test @@ -396,9 +353,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -408,22 +362,20 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - try { - task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + final TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.05", - ((EaafException) e.getOriginalException()).getErrorId()); + Assert.assertNotNull(e.getPendingRequestID()); + Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + Assert.assertNotNull(e.getOriginalException()); + org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, + e.getOriginalException()); + Assert.assertEquals("sp.pvp2.05", + ((EaafException) e.getOriginalException()).getErrorId()); - } } @Test @@ -431,9 +383,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException, TaskExecutionException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -443,12 +392,13 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - //perform test + // perform test task.execute(pendingReq, executionContext); - //validate state + // validate state Assert.assertTrue("process not cancelled", executionContext.isProcessCancelled()); Assert.assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); Assert.assertFalse("should not authenticated", pendingReq.isAuthenticated()); @@ -460,9 +410,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -472,7 +419,8 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); try { task.execute(pendingReq, executionContext); @@ -495,9 +443,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -507,7 +452,8 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); try { task.execute(pendingReq, executionContext); @@ -530,9 +476,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -542,57 +485,27 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - //put SimpleEidasData in session + // put SimpleEidasData in session final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = new SimpleEidasData(); + final SimpleEidasData eidData = new SimpleEidasData(); eidData.setFamilyName("Mustermann"); eidData.setGivenName("Max"); eidData.setDateOfBirth("1940-01-01"); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - //perform task + // perform task task.execute(pendingReq, executionContext); - //validate state -// Assert.assertTrue("Wrong EID-Process flag", -// (boolean) executionContext.get(AuthHandlerConstants.PROCESSCONTEXT_WAS_EID_PROCESS)); -// Assert.assertFalse("Wrong Mandate flag", -// (boolean) executionContext.get(AuthHandlerConstants.HTTP_PARAM_USE_MANDATES)); - -// Assert.assertEquals("piiTransactionId", "piiId_112233445566", pendingReq.getUniquePiiTransactionIdentifier()); - + // validate state final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); - -// Assert.assertTrue("E-ID flag", session.isEidProcess()); -// Assert.assertTrue("Foreign flag", session.isForeigner()); -// Assert.assertEquals("eidasBind", EIDAS_BIND, session.getQcBind()); -// Assert.assertEquals("vsz", -// "OD/kCGIFbjLTW0po6IZSmoaz3uhPYlO3S5bs9JnK0A5DHtufM3APLuDc3Llp4PeNdEa4NrCmgHr1YUiHT5irT8eDAfGpIbQHJg==", -// session.getVsz()); -// Assert.assertArrayEquals("signedConsent", -// Base64.getDecoder().decode(TEST_SIGNED_AUTHBLOCK), session.getSignedAuthBlock()); -// Assert.assertEquals("AuthBlockType", AuthHandlerConstants.AuthBlockType.JWS, session.getSignedAuthBlockType()); - Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); -// Assert.assertEquals("CountryCode", "IT", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); -// Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); - -// Assert.assertFalse("Mandate flag", session.isMandateUsed()); -// Assert.assertNull("MandateInfos", session.getMandateDate()); + //TODO: - Assert.assertNull("MandateType", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_TYPE_NAME, String.class)); - Assert.assertNull("Legal Person CommonName", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_FULL_NAME_NAME, String.class)); - Assert.assertNull("Legal Person SourcePin",session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_NAME, String.class)); - Assert.assertNull("Legal Person SourcePinType", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class)); } @Test @@ -600,9 +513,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -612,17 +522,18 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { credentialProvider.getMessageSigningCredential(), true); httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); + DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( + "UTF-8"))); - //put SimpleEidasData in session + // put SimpleEidasData in session final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = new SimpleEidasData(); + final SimpleEidasData eidData = new SimpleEidasData(); eidData.setFamilyName("Mustermann1"); eidData.setGivenName("Max"); eidData.setDateOfBirth("1940-01-01"); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - //perform task + // perform task try { task.execute(pendingReq, executionContext); Assert.fail("Invalid response not detected"); @@ -634,171 +545,18 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); Assert.assertTrue(e.getOriginalException().getCause() instanceof InvalidUserInputException); - } - - } - - @Test - public void httpPostValidSignedAssertionLegacyValid() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { -// authConfig.putConfigValue(AuthHandlerConstants.PROP_CONFIG_LEGACY_ALLOW, "true"); - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - //put SimpleEidasData in session - final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = new SimpleEidasData(); - eidData.setFamilyName("Mustermann"); - eidData.setGivenName("Max"); - eidData.setDateOfBirth("1940-01-01"); - authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_legacy.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); - - String piiTransId = pendingReq.getUniquePiiTransactionIdentifier(); - - //perform task - task.execute(pendingReq, executionContext); - - //validate state -// Assert.assertFalse("Wrong EID-Process flag", -// (boolean) executionContext.get(AuthHandlerConstants.PROCESSCONTEXT_WAS_EID_PROCESS)); -// Assert.assertFalse("Wrong Mandate flag", -// (boolean) executionContext.get(AuthHandlerConstants.HTTP_PARAM_USE_MANDATES)); - - Assert.assertEquals("piiTransactionId", piiTransId, pendingReq.getUniquePiiTransactionIdentifier()); - - final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); - - Assert.assertFalse("E-ID flag", session.isEidProcess()); -// Assert.assertTrue("Foreign flag", session.isForeigner()); - Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/test", session.getQaaLevel()); -// Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); - Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); - -// Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); -// Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); -// Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); -// -// Assert.assertEquals("bPK", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); -// Assert.assertEquals("bPK-Target", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); -// Assert.assertEquals("AuthBlock", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); - -// Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); -// Assert.assertNull("eidasBind", session.getQcBind()); -// Assert.assertNull("signedConsent", session.getSignedAuthBlock()); -// Assert.assertEquals("signedConsentType", AuthBlockType.NONE, session.getSignedAuthBlockType()); - - Assert.assertFalse("Mandate flag", session.isMandateUsed()); -// Assert.assertNull("MandateInfos", session.getMandateDate()); - - } - - @Test - public void httpPostValidSignedAssertionWithLegacyAndEid() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { - - oaParam.putGenericConfigurationKey( - IdAustriaClientAuthConstants.CONFIG_PROPS_APPSPECIFIC_EIDAS_NODE_URL, METADATA_PATH); - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - //put SimpleEidasData in session - final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = new SimpleEidasData(); - eidData.setFamilyName("Mustermann"); - eidData.setGivenName("Max"); - eidData.setDateOfBirth("1940-01-01"); - authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_legacy_and_EID.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes("UTF-8"))); - - //perform task - task.execute(pendingReq, executionContext); - - //validate state -// Assert.assertTrue("Wrong EID-Process flag", -// (boolean) executionContext.get(AuthHandlerConstants.PROCESSCONTEXT_WAS_EID_PROCESS)); - final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); -// Assert.assertFalse("Wrong Mandate flag", -// (boolean) executionContext.get(AuthHandlerConstants.HTTP_PARAM_USE_MANDATES)); - -// Assert.assertTrue("E-ID flag", session.isEidProcess()); -// Assert.assertTrue("Foreign flag", session.isForeigner()); - Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/test", session.getQaaLevel()); -// Assert.assertEquals("CountryCode", "AB", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class)); - Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); - -// Assert.assertEquals("eidasBind", EIDAS_BIND, session.getQcBind()); -// Assert.assertArrayEquals("signedConsent", -// Base64.getDecoder().decode(TEST_SIGNED_AUTHBLOCK), session.getSignedAuthBlock()); - -// Assert.assertEquals("FamilyName", "Mustermann", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); -// Assert.assertEquals("Givenname", "Max", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.GIVEN_NAME_NAME, String.class)); -// Assert.assertEquals("DateOfBirth", "1940-01-01", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.BIRTHDATE_NAME, String.class)); -// -// Assert.assertEquals("FamilyName", "BF:QVGm48cqcM4UcyhDTNGYmVdrIoY=", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.BPK_NAME, String.class)); -// Assert.assertEquals("FamilyName", "urn:publicid:gv.at:cdid+BF", session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)); -// Assert.assertEquals("FamilyName", TEST_SIGNED_AUTHBLOCK, session.getGenericDataFromSession( -// ExtendedPvpAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class)); - -// Assert.assertNull("SigCert", session.getEncodedSignerCertificate()); - - Assert.assertFalse("Mandate flag", session.isMandateUsed()); -// Assert.assertNull("MandateInfos", session.getMandateDate()); - - Assert.assertNull("MandateType", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_TYPE_NAME, String.class)); - Assert.assertNull("Legal Person CommonName", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_FULL_NAME_NAME, String.class)); - Assert.assertNull("Legal Person SourcePin",session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_NAME, String.class)); - Assert.assertNull("Legal Person SourcePinType", session.getGenericDataFromSession( - ExtendedPvpAttributeDefinitions.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class)); + } } - - - private Response initializeResponse(String idpEntityId, String responsePath, EaafX509Credential credential, - boolean validConditions) throws SamlSigningException, XMLParserException, UnmarshallingException, + boolean validConditions) throws SamlSigningException, XMLParserException, UnmarshallingException, Pvp2MetadataException { final Response response = (Response) XMLObjectSupport.unmarshallFromInputStream( XMLObjectProviderRegistrySupport.getParserPool(), - ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.class.getResourceAsStream(responsePath)); + ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.class.getResourceAsStream( + responsePath)); response.setIssueInstant(DateTime.now()); final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class); issuer.setValue(idpEntityId); -- cgit v1.2.3 From 84244f4ac1909c20ce36531f110705b24edbad12 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 22 Feb 2021 10:43:57 +0100 Subject: Rename tasks to clarify functionality --- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 8 +- .../ReceiveLoginMethodGuiResponseTaskTest.java | 139 --------------------- ...ReceiveOtherLoginMethodGuiResponseTaskTest.java | 135 ++++++++++++++++++++ 3 files changed, 139 insertions(+), 143 deletions(-) delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveOtherLoginMethodGuiResponseTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index 95986c49..e0138f62 100644 --- 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 @@ -386,7 +386,7 @@ public class InitialSearchTaskTest { .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", null, bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); Assert.assertEquals("Wrong transition", null, transitionGUI); Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); Assert.assertEquals("Wrong transition", true, transitionErnb); @@ -411,7 +411,7 @@ public class InitialSearchTaskTest { pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", null, bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); Assert.assertEquals("Wrong transition", true, transitionGUI); Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); Assert.assertEquals("Wrong transition", null, transitionErnb); @@ -436,7 +436,7 @@ public class InitialSearchTaskTest { pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", null, bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); Assert.assertEquals("Wrong transition", true, transitionGUI); Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); Assert.assertEquals("Wrong transition", null, transitionErnb); @@ -463,7 +463,7 @@ public class InitialSearchTaskTest { pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); Assert.assertEquals("Wrong bpk", null, bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_GENERATE_GUI_TASK); + Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); Assert.assertEquals("Wrong transition", true, transitionGUI); Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); Assert.assertEquals("Wrong transition", null, transitionErnb); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java deleted file mode 100644 index c6729a03..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveLoginMethodGuiResponseTaskTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; - -import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SelectedLoginMethod; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveLoginMethodGuiResponseTask; -import at.gv.egiz.eaaf.core.api.data.EaafConstants; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.controller.tasks.AbstractLocaleAuthServletTask; -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.Assert; -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 java.io.UnsupportedEncodingException; - -@RunWith(SpringJUnit4ClassRunner.class) -//@ContextConfiguration({ -// "/applicationContext.xml", -// "/specific_eIDAS_connector.beans.xml", -// "/eaaf_core.beans.xml", -// "/eaaf_pvp.beans.xml", -// "/eaaf_pvp_idp.beans.xml", -// "/spring/SpringTest-context_simple_storage.xml" }) -@ContextConfiguration(locations = { - "/SpringTest-context_tasks_test.xml", - "/SpringTest-context_basic_mapConfig.xml" -}) -@ActiveProfiles(profiles = {"deprecatedConfig"}) -@WebAppConfiguration -public class ReceiveLoginMethodGuiResponseTaskTest { - - @Autowired private ReceiveLoginMethodGuiResponseTask task; - - private 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 { - test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); - } - - @Test - public void withEidasSelection() throws TaskExecutionException { - test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); - } - - @Test - public void withNoOtherLoginSelection() throws TaskExecutionException { - test(SelectedLoginMethod.NO_OTHER_LOGIN); - } - - public void test(SelectedLoginMethod loginMethod) throws TaskExecutionException { - String parameterValue = loginMethod.name(); - httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); - - task.execute(pendingReq, executionContext); - - //result validation - Assert.assertFalse("wrong pendingReq auth flag", pendingReq.isAuthenticated()); - Assert.assertFalse("wrong process-cancelled flag", executionContext.isProcessCancelled()); - - Assert.assertNotNull("no login-selection found", - executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); - Assert.assertEquals("Wrong login-selection found", loginMethod, - executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); - } - - - @Test(expected = TaskExecutionException.class) - public void withInvalidSelection() throws TaskExecutionException { - String parameterValue = RandomStringUtils.randomAlphabetic(2); - httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); - task.execute(pendingReq, executionContext); - } - - @Test(expected = TaskExecutionException.class) - public void withNullSelection() throws TaskExecutionException { - httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, "null"); - task.execute(pendingReq, executionContext); - } - - @Test(expected = TaskExecutionException.class) - public void withEmptySelection() throws TaskExecutionException { - httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, ""); - task.execute(pendingReq, executionContext); - } - - @Test(expected = TaskExecutionException.class) - public void withoutLoginMethodSelection() throws TaskExecutionException, UnsupportedEncodingException { - task.execute(pendingReq, executionContext); - } -} 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..ae4b5d8c --- /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,135 @@ +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.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.Assert; +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 java.io.UnsupportedEncodingException; + +@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration({ +// "/applicationContext.xml", +// "/specific_eIDAS_connector.beans.xml", +// "/eaaf_core.beans.xml", +// "/eaaf_pvp.beans.xml", +// "/eaaf_pvp_idp.beans.xml", +// "/spring/SpringTest-context_simple_storage.xml" }) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" +}) +@ActiveProfiles(profiles = {"deprecatedConfig"}) +@WebAppConfiguration +public class ReceiveOtherLoginMethodGuiResponseTaskTest { + + @Autowired private ReceiveOtherLoginMethodGuiResponseTask task; + + private 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 { + test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); + } + + @Test + public void withEidasSelection() throws TaskExecutionException { + test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); + } + + @Test + public void withNoOtherLoginSelection() throws TaskExecutionException { + test(SelectedLoginMethod.NO_OTHER_LOGIN); + } + + public void test(SelectedLoginMethod loginMethod) throws TaskExecutionException { + String parameterValue = loginMethod.name(); + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); + + task.execute(pendingReq, executionContext); + + //result validation + Assert.assertFalse("wrong pendingReq auth flag", pendingReq.isAuthenticated()); + Assert.assertFalse("wrong process-cancelled flag", executionContext.isProcessCancelled()); + + Assert.assertNotNull("no login-selection found", + executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); + Assert.assertEquals("Wrong login-selection found", loginMethod, + executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); + } + + + @Test(expected = TaskExecutionException.class) + public void withInvalidSelection() throws TaskExecutionException { + String parameterValue = RandomStringUtils.randomAlphabetic(2); + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); + task.execute(pendingReq, executionContext); + } + + @Test(expected = TaskExecutionException.class) + public void withNullSelection() throws TaskExecutionException { + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, "null"); + task.execute(pendingReq, executionContext); + } + + @Test(expected = TaskExecutionException.class) + public void withEmptySelection() throws TaskExecutionException { + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, ""); + task.execute(pendingReq, executionContext); + } + + @Test(expected = TaskExecutionException.class) + public void withoutLoginMethodSelection() throws TaskExecutionException, UnsupportedEncodingException { + task.execute(pendingReq, executionContext); + } +} -- cgit v1.2.3 From 3c838c11bc536a7418654989752b94b457d3f52f Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 22 Feb 2021 11:36:03 +0100 Subject: Refactor test for InitialSearchTask --- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 104 ++++++++++----------- 1 file changed, 50 insertions(+), 54 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index e0138f62..d855c98d 100644 --- 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 @@ -41,7 +41,6 @@ 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.protocol.impl.AuthenticationResponse; -import lombok.val; import org.apache.commons.lang3.RandomStringUtils; import org.jetbrains.annotations.NotNull; import org.junit.Assert; @@ -67,6 +66,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Random; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.junit.Assert.assertThrows; @RunWith(SpringJUnit4ClassRunner.class) @@ -91,24 +91,12 @@ public class InitialSearchTaskTest { private final String randomBpk = RandomStringUtils.randomNumeric(6); private final String randomIdentifier = RandomStringUtils.randomNumeric(10); private final String randomPseudonym = DE_ST + randomIdentifier; - private final String randomFamilyName = RandomStringUtils.randomAlphabetic(10); - private final String randomGivenName = RandomStringUtils.randomAlphabetic(10); - private final String randomPlaceOfBirth = RandomStringUtils.randomAlphabetic(10); - private final String randomBirthName = RandomStringUtils.randomAlphabetic(10); + 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 class initializer. -// * -// * @throws IOException In case of an error -// */ -// @BeforeClass -// public static void classInitializer() throws IOException { -// final String current = new java.io.File(".").toURI().toString(); -// System.setProperty("eidas.ms.configuration", current -// + "src/test/resources/config/junit_config_1.properties"); -// } - /** * jUnit test set-up. */ @@ -134,7 +122,7 @@ public class InitialSearchTaskTest { @Test @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - String newFirstName = RandomStringUtils.randomAlphabetic(10); + String newFirstName = randomAlphabetic(10); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( new RegisterResult(randomBpk, randomIdentifier, newFirstName, randomFamilyName, randomBirthDate))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -154,7 +142,7 @@ public class InitialSearchTaskTest { @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - String newRandomGivenName = RandomStringUtils.randomAlphabetic(10); + String newRandomGivenName = randomAlphabetic(10); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate))); @@ -174,7 +162,7 @@ public class InitialSearchTaskTest { public void testNode101_ManualFixNecessary_a() { ArrayList zmrResult = new ArrayList<>(); zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate)); - String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + String newRandomGivenName = randomGivenName + randomAlphabetic(2); zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate)); Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); @@ -196,7 +184,7 @@ public class InitialSearchTaskTest { Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); ArrayList ernpResult = new ArrayList<>(); ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomBirthDate)); - String newRandomGivenName = randomGivenName + RandomStringUtils.randomAlphabetic(2); + String newRandomGivenName = randomGivenName + randomAlphabetic(2); ernpResult.add( new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); @@ -384,12 +372,12 @@ public class InitialSearchTaskTest { String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", null, bPk); + Assert.assertNull("Wrong bpk", bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); - Assert.assertEquals("Wrong transition", null, transitionGUI); - Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); - Assert.assertEquals("Wrong transition", true, transitionErnb); + 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_ERNB_ENTRY_TASK); + Assert.assertTrue("Wrong transition", transitionErnb); } /** @@ -403,18 +391,18 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn( Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); + new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); task.execute(pendingReq, executionContext); String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", null, bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); - Assert.assertEquals("Wrong transition", true, transitionGUI); - Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); - Assert.assertEquals("Wrong transition", null, transitionErnb); + Assert.assertNull("Wrong bpk", bPk); + 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_ERNB_ENTRY_TASK); + Assert.assertNull("Wrong transition", transitionErnb); } /** @@ -435,11 +423,11 @@ public class InitialSearchTaskTest { String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", null, bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); - Assert.assertEquals("Wrong transition", true, transitionGUI); - Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); - Assert.assertEquals("Wrong transition", null, transitionErnb); + Assert.assertNull("Wrong bpk", bPk); + 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_ERNB_ENTRY_TASK); + Assert.assertNull("Wrong transition", transitionErnb); } /** @@ -453,7 +441,7 @@ public class InitialSearchTaskTest { ArrayList ernbResult = new ArrayList<>(); ernbResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate)); - ernbResult.add(new RegisterResult(randomBpk+"1", randomIdentifier, randomGivenName, randomFamilyName, + ernbResult.add(new RegisterResult(randomBpk + "1", randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate)); Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn(ernbResult); @@ -462,11 +450,11 @@ public class InitialSearchTaskTest { String bPk = (String) pendingReq.getSessionData(AuthProcessDataWrapper.class) .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); - Assert.assertEquals("Wrong bpk", null, bPk); - Boolean transitionGUI = (Boolean)executionContext.get(Constants.TRANSITION_TO_GENERATE_OTHER_LOGIN_METHOD_GUI_TASK); - Assert.assertEquals("Wrong transition", true, transitionGUI); - Boolean transitionErnb = (Boolean)executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNB_ENTRY_TASK); - Assert.assertEquals("Wrong transition", null, transitionErnb); + Assert.assertNull("Wrong bpk", bPk); + 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_ERNB_ENTRY_TASK); + Assert.assertNull("Wrong transition", transitionErnb); } @NotNull @@ -498,25 +486,32 @@ public class InitialSearchTaskTest { String dateOfBirth, String taxNumber, String placeOfBirth, String birthName) throws URISyntaxException { ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder() - .put(generateStringAttribute(Constants.eIDAS_ATTR_PERSONALIDENTIFIER, "ff", "af"), identifier) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTFAMILYNAME, "fff", "aff"), familyName) - .put(generateStringAttribute(Constants.eIDAS_ATTR_CURRENTGIVENNAME, "ffff", "afff"), givenName) - .put(generateDateTimeAttribute(Constants.eIDAS_ATTR_DATEOFBIRTH, "fffff", "affff"), dateOfBirth); + .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, "ffffff", "afffff"), taxNumber); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_TAXREFERENCE, + randomAlphabetic(6), randomAlphabetic(6)), taxNumber); } if (birthName != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME, "fffffff", "affffff"), birthName); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_BIRTHNAME, + randomAlphabetic(7), randomAlphabetic(7)), birthName); } if (placeOfBirth != null) { - builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH, "ffffffff", "afffffff"), - placeOfBirth); + builder.put(generateStringAttribute(Constants.eIDAS_ATTR_PLACEOFBIRTH, + randomAlphabetic(8), randomAlphabetic(8)), placeOfBirth); } final ImmutableAttributeMap attributeMap = builder.build(); - val b = new AuthenticationResponse.Builder(); - return b.id("aasdf").issuer("asd").subject("asf").statusCode("200").inResponseTo("asdf").subjectNameIdFormat( - "afaf").attributes(attributeMap).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 generateStringAttribute(String friendlyName, String fragment, String prefix) @@ -525,6 +520,7 @@ public class InitialSearchTaskTest { ".LiteralStringAttributeValueMarshaller"); } + @SuppressWarnings("SameParameterValue") private AttributeDefinition generateDateTimeAttribute(String friendlyName, String fragment, String prefix) throws URISyntaxException { return generateAttribute(friendlyName, fragment, prefix, "eu.eidas.auth.commons.attribute.impl" + -- cgit v1.2.3 From 39b5e38cc5e3c7c555ae10e0ff0f684c9bcc0966 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 22 Feb 2021 13:57:50 +0100 Subject: Add service to consolidate register search access --- .../auth/eidas/v2/test/tasks/InitialSearchTaskTest.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index d855c98d..ae2bc93e 100644 --- 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 @@ -29,6 +29,7 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.ernp.IErnpClient; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService; import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; @@ -85,6 +86,7 @@ public class InitialSearchTaskTest { private IZmrClient zmrClient; @Mock private IErnpClient ernpClient; + private RegisterSearchService registerSearchService; final ExecutionContext executionContext = new ExecutionContextImpl(); private TestRequestImpl pendingReq; @@ -103,7 +105,8 @@ public class InitialSearchTaskTest { @Before public void setUp() throws URISyntaxException, EaafStorageException { MockitoAnnotations.initMocks(this); - task = new InitialSearchTask(new ArrayList<>(), ernpClient, zmrClient); + registerSearchService = new RegisterSearchService(zmrClient, ernpClient); + task = new InitialSearchTask(new ArrayList<>(), registerSearchService, ernpClient, zmrClient); MockHttpServletRequest httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); MockHttpServletResponse httpResp = new MockHttpServletResponse(); @@ -250,7 +253,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + registerSearchService, ernpClient, zmrClient); task.execute(pendingReq1, executionContext); @@ -280,7 +283,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + registerSearchService, ernpClient, zmrClient); task.execute(pendingReq1, executionContext); @@ -316,7 +319,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + registerSearchService, ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); @@ -349,7 +352,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - ernpClient, zmrClient); + registerSearchService, ernpClient, zmrClient); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); -- cgit v1.2.3 From 5eb83e0ca367958c81a7b0ee2cbd047482dd1974 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 22 Feb 2021 14:06:16 +0100 Subject: Move country specific search in registers into common service --- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index ae2bc93e..4dd6b92e 100644 --- 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 @@ -106,7 +106,7 @@ public class InitialSearchTaskTest { public void setUp() throws URISyntaxException, EaafStorageException { MockitoAnnotations.initMocks(this); registerSearchService = new RegisterSearchService(zmrClient, ernpClient); - task = new InitialSearchTask(new ArrayList<>(), registerSearchService, ernpClient, zmrClient); + task = new InitialSearchTask(new ArrayList<>(), registerSearchService); MockHttpServletRequest httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); MockHttpServletResponse httpResp = new MockHttpServletResponse(); @@ -252,8 +252,8 @@ public class InitialSearchTaskTest { randomBirthDate, null, null, taxNumber, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( - Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - registerSearchService, ernpClient, zmrClient); + Collections.singletonList(new ItSpecificDetailSearchProcessor(registerSearchService)), + registerSearchService); task.execute(pendingReq1, executionContext); @@ -282,8 +282,8 @@ public class InitialSearchTaskTest { randomFamilyName, randomBirthDate, randomPlaceOfBirth, randomBirthName, null, null))); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( - Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - registerSearchService, ernpClient, zmrClient); + Collections.singletonList(new DeSpecificDetailSearchProcessor(registerSearchService)), + registerSearchService); task.execute(pendingReq1, executionContext); @@ -318,8 +318,8 @@ public class InitialSearchTaskTest { randomBirthName)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( - Collections.singletonList(new DeSpecificDetailSearchProcessor(ernpClient, zmrClient)), - registerSearchService, ernpClient, zmrClient); + Collections.singletonList(new DeSpecificDetailSearchProcessor(registerSearchService)), + registerSearchService); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); @@ -351,8 +351,8 @@ public class InitialSearchTaskTest { Mockito.when(zmrClient.searchItSpecific(randomTaxNumber)).thenReturn(zmrResultSpecific); Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( - Collections.singletonList(new ItSpecificDetailSearchProcessor(ernpClient, zmrClient)), - registerSearchService, ernpClient, zmrClient); + Collections.singletonList(new ItSpecificDetailSearchProcessor(registerSearchService)), + registerSearchService); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); -- cgit v1.2.3 From 0725cce166b91725624e4cde694e9fde4e931bc9 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 22 Feb 2021 14:31:47 +0100 Subject: Refactor exception throwing and some names --- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 60 ++++++++-------------- 1 file changed, 22 insertions(+), 38 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index 4dd6b92e..c9f123dc 100644 --- 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 @@ -131,9 +131,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -150,9 +148,7 @@ public class InitialSearchTaskTest { new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate))); task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -174,7 +170,7 @@ public class InitialSearchTaskTest { () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); } @@ -196,7 +192,7 @@ public class InitialSearchTaskTest { () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); } /** @@ -210,9 +206,7 @@ public class InitialSearchTaskTest { new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -228,9 +222,7 @@ public class InitialSearchTaskTest { task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -257,9 +249,7 @@ public class InitialSearchTaskTest { task.execute(pendingReq1, executionContext); - String bPk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq1); Assert.assertEquals("Wrong bpk", bPk, randomBpk); } @@ -287,9 +277,7 @@ public class InitialSearchTaskTest { task.execute(pendingReq1, executionContext); - String resultBpk = (String) - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String resultBpk = readBpkFromSessionData(pendingReq1); Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); } @@ -325,7 +313,7 @@ public class InitialSearchTaskTest { () -> task.execute(pendingReq1, executionContext)); Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); } /** @@ -358,7 +346,7 @@ public class InitialSearchTaskTest { () -> task.execute(pendingReq1, executionContext)); Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE.getCause() instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); } /** @@ -372,14 +360,12 @@ public class InitialSearchTaskTest { task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertNull("Wrong bpk", bPk); 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_ERNB_ENTRY_TASK); + Boolean transitionErnb = (Boolean) executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK); Assert.assertTrue("Wrong transition", transitionErnb); } @@ -398,13 +384,11 @@ public class InitialSearchTaskTest { task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertNull("Wrong bpk", bPk); 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_ERNB_ENTRY_TASK); + Boolean transitionErnb = (Boolean) executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK); Assert.assertNull("Wrong transition", transitionErnb); } @@ -423,13 +407,11 @@ public class InitialSearchTaskTest { task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertNull("Wrong bpk", bPk); 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_ERNB_ENTRY_TASK); + Boolean transitionErnb = (Boolean) executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK); Assert.assertNull("Wrong transition", transitionErnb); } @@ -450,13 +432,11 @@ public class InitialSearchTaskTest { task.execute(pendingReq, executionContext); - String bPk = (String) - pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + String bPk = readBpkFromSessionData(pendingReq); Assert.assertNull("Wrong bpk", bPk); 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_ERNB_ENTRY_TASK); + Boolean transitionErnb = (Boolean) executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK); Assert.assertNull("Wrong transition", transitionErnb); } @@ -538,4 +518,8 @@ public class InitialSearchTaskTest { .attributeValueMarshaller(marshaller).build(); } + private String readBpkFromSessionData(TestRequestImpl pendingReq) { + return (String) pendingReq.getSessionData(AuthProcessDataWrapper.class) + .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + } } -- cgit v1.2.3 From 3338a3dd00fabf28f1de8579535b1626dbe99908 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 22 Feb 2021 15:46:10 +0100 Subject: Refactor tasks for MobilePhoneSignature login --- .../modules/auth/eidas/v2/test/dummy/DummyOA.java | 18 +- ...enerateMobilePhoneSignatureRequestTaskTest.java | 118 +++++----- ...natureResponseAndSearchInRegistersTaskTest.java | 256 +++++++++------------ 3 files changed, 175 insertions(+), 217 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index cf879562..2f7782ae 100644 --- 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 @@ -1,21 +1,15 @@ 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 org.apache.commons.lang3.StringUtils; - import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; - import lombok.Getter; import lombok.Setter; +import org.apache.commons.lang3.StringUtils; + +import java.util.*; -public class DummyOA implements IAhSpConfiguration{ +public class DummyOA implements IAhSpConfiguration { private static final long serialVersionUID = 1L; private String uniqueAppId = null; @@ -74,7 +68,7 @@ public class DummyOA implements IAhSpConfiguration{ @Override public boolean isConfigurationValue(final String key) { if (StringUtils.isNotEmpty(getConfigurationValue(key))) { - return Boolean.valueOf(getConfigurationValue(key)); + return Boolean.parseBoolean(getConfigurationValue(key)); } else { return false; } @@ -258,7 +252,7 @@ public class DummyOA implements IAhSpConfiguration{ @Override public boolean isRestrictedServiceProvider() { - return this.restricted ; + return this.restricted; } 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 index 4fb05a35..8e5ecfe1 100644 --- 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 @@ -1,31 +1,5 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import static org.junit.Assert.assertThrows; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.Base64; -import java.util.Map; - -import org.apache.commons.lang3.RandomStringUtils; -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.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 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; @@ -48,6 +22,34 @@ import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xIniti 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 = { @@ -140,13 +142,10 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, - e.getOriginalException()); - Assert.assertEquals("module.eidasauth.00", - ((EaafConfigurationException) e.getOriginalException()).getErrorId()); - + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(EaafConfigurationException.class, e.getOriginalException()); + assertEquals("module.eidasauth.00", ((EaafConfigurationException) e.getOriginalException()).getErrorId()); } @Test @@ -156,14 +155,12 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, - e.getOriginalException()); - Assert.assertEquals("module.eidasauth.idaustria.02", + 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 @@ -175,14 +172,12 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(CredentialsNotAvailableException.class, - e.getOriginalException()); - Assert.assertEquals("internal.pvp.01", + 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 @@ -198,33 +193,33 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { } private void validate() throws Exception { - Assert.assertEquals("HTTP Statuscode", 200, httpResp.getStatus()); - Assert.assertEquals("ContentType", "text/html;charset=UTF-8", httpResp.getContentType()); - Assert.assertEquals("ContentEncoding", "UTF-8", httpResp.getCharacterEncoding()); + 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(); - Assert.assertNotNull("XML Metadata", html); + assertNotNull("XML Metadata", html); final int startIndex = html.indexOf("SAMLRequest="); - Assert.assertTrue("No SAMLRequest in html", startIndex >= 0); + 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="); - Assert.assertTrue("wrong RelayState in HTML", + assertTrue("wrong RelayState in HTML", startIndexRelayState >= 0); final String relayState = html.substring(startIndexRelayState + "RelayState=".length(), startIndex); final String storedPendingReqId = transactionStorage.get(relayState, String.class); - Assert.assertEquals("relayStore not map to pendingRequestId", + assertEquals("relayStore not map to pendingRequestId", pendingReq.getPendingRequestId(), storedPendingReqId); final AuthnRequest authnRequest = (AuthnRequest) XMLObjectSupport.unmarshallFromInputStream( XMLObjectProviderRegistrySupport.getParserPool(), new ByteArrayInputStream( Base64.getDecoder().decode(authnXml))); - Assert.assertNotNull("AuthnReq", authnRequest); - Assert.assertNotNull("Issuer", authnRequest.getIssuer()); - Assert.assertEquals("EntityId", + assertNotNull("AuthnReq", authnRequest); + assertNotNull("Issuer", authnRequest.getIssuer()); + assertEquals("EntityId", "https://localhost/authhandler" + IdAustriaClientAuthConstants.ENDPOINT_METADATA, authnRequest.getIssuer().getValue()); @@ -240,12 +235,11 @@ public class GenerateMobilePhoneSignatureRequestTaskTest { metadataFactory.createMetadataProvider(METADATA_SP_PATH, null, "jUnit SP", null)); samlVerifyEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); - Assert.assertNotNull("RequestedAuthnContext", authnRequest.getRequestedAuthnContext()); - Assert.assertNotNull("AuthnContextClassRef", - authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs()); - Assert.assertEquals("#AuthnContextClassRef", 1, + assertNotNull("RequestedAuthnContext", authnRequest.getRequestedAuthnContext()); + assertNotNull("AuthnContextClassRef", authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs()); + assertEquals("#AuthnContextClassRef", 1, authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().size()); - Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/high", + assertEquals("LoA", "http://eidas.europa.eu/LoA/high", authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef()); } diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java index fb34a2dd..42dd3ddc 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java @@ -1,35 +1,5 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import static org.junit.Assert.assertThrows; - -import java.io.IOException; -import java.util.Base64; - -import javax.xml.transform.TransformerException; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.joda.time.DateTime; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; -import org.opensaml.core.xml.io.MarshallingException; -import org.opensaml.core.xml.io.UnmarshallingException; -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.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 at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; @@ -57,6 +27,39 @@ import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xIniti 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.XMLParserException; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.io.UnmarshallingException; +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.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 javax.xml.transform.TransformerException; +import java.io.IOException; +import java.util.Base64; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.springframework.util.Assert.isInstanceOf; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { @@ -67,9 +70,9 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; - @Autowired(required = true) + @Autowired private ApplicationContext context; - @Autowired(required = true) + @Autowired protected MsConnectorDummyConfigMap authConfig; @Autowired private IdAustriaClientAuthMetadataProvider metadataProvider; @@ -78,11 +81,10 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { @Autowired private PvpMetadataResolverFactory metadataFactory; - final ExecutionContext executionContext = new ExecutionContextImpl(); + private final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; private MockHttpServletResponse httpResp; private DummyPendingRequest pendingReq; - private DummyOA oaParam; private ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask task; @@ -115,13 +117,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, - METADATA_PATH); + authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, METADATA_PATH); - oaParam = new DummyOA(); + DummyOA oaParam = new DummyOA(); oaParam.setUniqueAppId("http://test.com/test"); - oaParam.setTargetIdentifier( - EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); + oaParam.setTargetIdentifier(EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); pendingReq = new DummyPendingRequest(); pendingReq.initialize(httpReq, authConfig); @@ -129,7 +129,6 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { pendingReq.setOnlineApplicationConfiguration(oaParam); metadataProvider.fullyDestroy(); - } @Test @@ -141,14 +140,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.03", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.03", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); } @Test @@ -160,13 +156,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); } @@ -175,14 +169,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); } @Test @@ -195,13 +186,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); } @@ -221,13 +210,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); } @@ -246,14 +233,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.11", - ((EaafException) e.getOriginalException()).getErrorId()); - + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.11", ((EaafException) e.getOriginalException()).getErrorId()); } @Test @@ -275,13 +259,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((EaafException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); } @@ -292,7 +274,7 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, "http://wrong.idp/" + RandomStringUtils.randomAlphabetic(5)); - + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); @@ -308,13 +290,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.08", - ((EaafException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.08", ((EaafException) e.getOriginalException()).getErrorId()); } @@ -338,13 +318,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.12", - ((EaafException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); } @@ -368,13 +346,11 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { final TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.05", - ((EaafException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); } @@ -399,9 +375,9 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { task.execute(pendingReq, executionContext); // validate state - Assert.assertTrue("process not cancelled", executionContext.isProcessCancelled()); - Assert.assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); - Assert.assertFalse("should not authenticated", pendingReq.isAuthenticated()); + assertTrue("process not cancelled", executionContext.isProcessCancelled()); + assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); + assertFalse("should not authenticated", pendingReq.isAuthenticated()); } @@ -424,17 +400,14 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { try { task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + fail("Invalid response not detected"); } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.05", - ((EaafException) e.getOriginalException()).getErrorId()); - + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); } } @@ -457,16 +430,14 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { try { task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + fail("Invalid response not detected"); } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertEquals("sp.pvp2.05", - ((EaafException) e.getOriginalException()).getErrorId()); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); } } @@ -501,8 +472,8 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { // validate state final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); - Assert.assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); - Assert.assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); + assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); + assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); //TODO: @@ -536,15 +507,14 @@ public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { // perform task try { task.execute(pendingReq, executionContext); - Assert.fail("Invalid response not detected"); + fail("Invalid response not detected"); } catch (final TaskExecutionException e) { - Assert.assertNotNull(e.getPendingRequestID()); - Assert.assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - Assert.assertNotNull(e.getOriginalException()); - org.springframework.util.Assert.isInstanceOf(AuthnResponseValidationException.class, - e.getOriginalException()); - Assert.assertTrue(e.getOriginalException().getCause() instanceof InvalidUserInputException); + assertNotNull(e.getPendingRequestID()); + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + assertNotNull(e.getOriginalException()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertTrue(e.getOriginalException().getCause() instanceof InvalidUserInputException); } } -- cgit v1.2.3 From 0c4fe92684a707040fd7536da05945a64b309740 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 25 Feb 2021 07:54:53 +0100 Subject: Refactor tasks for MobilePhoneSignature login and tests --- ...natureResponseAndSearchInRegistersTaskTest.java | 543 --------------------- ...eceiveMobilePhoneSignatureResponseTaskTest.java | 371 ++++++++++++++ 2 files changed, 371 insertions(+), 543 deletions(-) delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java deleted file mode 100644 index 42dd3ddc..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.java +++ /dev/null @@ -1,543 +0,0 @@ -package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; - -import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyPendingRequest; -import at.gv.egiz.eaaf.core.api.data.EaafConstants; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EaafException; -import at.gv.egiz.eaaf.core.exceptions.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.process.ExecutionContextImpl; -import at.gv.egiz.eaaf.core.impl.utils.DomUtils; -import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential; -import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; -import at.gv.egiz.eaaf.modules.pvp2.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.sp.exception.AuthnResponseValidationException; -import net.shibboleth.utilities.java.support.xml.XMLParserException; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; -import org.opensaml.core.xml.io.MarshallingException; -import org.opensaml.core.xml.io.UnmarshallingException; -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.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 javax.xml.transform.TransformerException; -import java.io.IOException; -import java.util.Base64; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.springframework.util.Assert.isInstanceOf; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "/SpringTest-context_tasks_test.xml", - "/SpringTest-context_basic_mapConfig.xml" -}) -public class ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest { - - private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; - - @Autowired - private ApplicationContext context; - @Autowired - protected MsConnectorDummyConfigMap authConfig; - @Autowired - private IdAustriaClientAuthMetadataProvider metadataProvider; - @Autowired - private IdAustriaClientAuthCredentialProvider credentialProvider; - @Autowired - private PvpMetadataResolverFactory metadataFactory; - - private final ExecutionContext executionContext = new ExecutionContextImpl(); - private MockHttpServletRequest httpReq; - private MockHttpServletResponse httpResp; - private DummyPendingRequest pendingReq; - - private ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask 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 = (ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask) context.getBean( - "ReceiveMobilePhoneSignatureResponseTask"); - - 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 unsupportedHttpMethode() { - httpReq = new MockHttpServletRequest("PUT", "https://localhost/authhandler"); - RequestContextHolder.resetRequestAttributes(); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.03", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } - - @Test - public void httpGetNoMessage() { - httpReq = new MockHttpServletRequest("GET", "https://localhost/authhandler"); - RequestContextHolder.resetRequestAttributes(); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostNoMessage() { - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - } - - @Test - public void httpPostMessageNotSigned() throws IOException { - - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - IOUtils.toByteArray(ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTask.class - .getResourceAsStream( - "/data/Response_without_sig_classpath_entityid.xml")))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostMessageWrongDestinationEndpoint() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - TransformerException, MarshallingException { - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_wrong_destination_endpoint.xml", - credentialProvider.getMessageSigningCredential(), true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedNoMetadata() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.11", ((EaafException) e.getOriginalException()).getErrorId()); - } - - @Test - public void httpPostValidSignedAssertionOutDated() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), false); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedAssertionFromWrongIdp() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, - "http://wrong.idp/" + RandomStringUtils.randomAlphabetic(5)); - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.08", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedAssertionMissingAttributes() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_classpath_entityid.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedWithError() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - final TaskExecutionException e = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq, executionContext)); - - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); - - } - - @Test - public void httpPostValidSignedWitUserStopErrorCode() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error_userstop.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - // perform test - task.execute(pendingReq, executionContext); - - // validate state - assertTrue("process not cancelled", executionContext.isProcessCancelled()); - assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); - assertFalse("should not authenticated", pendingReq.isAuthenticated()); - - } - - @Test - public void httpPostValidSignedWithErrorAndNoSubCode() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error_without_subcode.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - try { - task.execute(pendingReq, executionContext); - fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); - } - } - - @Test - public void httpPostValidSignedWithErrorAndEmptySubCode() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_without_sig_with_error_empty_subcode.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - try { - task.execute(pendingReq, executionContext); - fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); - - } - } - - @Test - public void httpPostValidSignedAssertionEidValid() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_EID.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - // put SimpleEidasData in session - final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - final SimpleEidasData eidData = new SimpleEidasData(); - eidData.setFamilyName("Mustermann"); - eidData.setGivenName("Max"); - eidData.setDateOfBirth("1940-01-01"); - authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - - // perform task - task.execute(pendingReq, executionContext); - - // validate state - final AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); - assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); - assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); - - //TODO: - - } - - @Test - public void httpPostValidSignedAssertionEidValidButNameMissmatch() throws IOException, SamlSigningException, - Pvp2MetadataException, CredentialsNotAvailableException, XMLParserException, UnmarshallingException, - MarshallingException, TransformerException, TaskExecutionException, EaafStorageException { - - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); - - final Response response = initializeResponse( - "classpath:/data/idp_metadata_classpath_entity.xml", - "/data/Response_with_EID.xml", - credentialProvider.getMessageSigningCredential(), - true); - httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString( - DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)).getBytes( - "UTF-8"))); - - // put SimpleEidasData in session - final AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - final SimpleEidasData eidData = new SimpleEidasData(); - eidData.setFamilyName("Mustermann1"); - eidData.setGivenName("Max"); - eidData.setDateOfBirth("1940-01-01"); - authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - - // perform task - try { - task.execute(pendingReq, executionContext); - fail("Invalid response not detected"); - - } catch (final TaskExecutionException e) { - assertNotNull(e.getPendingRequestID()); - assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); - assertNotNull(e.getOriginalException()); - isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); - assertTrue(e.getOriginalException().getCause() instanceof InvalidUserInputException); - } - - } - - private Response initializeResponse(String idpEntityId, String responsePath, EaafX509Credential credential, - boolean validConditions) throws SamlSigningException, XMLParserException, UnmarshallingException, - Pvp2MetadataException { - - final Response response = (Response) XMLObjectSupport.unmarshallFromInputStream( - XMLObjectProviderRegistrySupport.getParserPool(), - ReceiveMobilePhoneSignatureResponseAndSearchInRegistersTaskTest.class.getResourceAsStream( - responsePath)); - response.setIssueInstant(DateTime.now()); - final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class); - issuer.setValue(idpEntityId); - response.setIssuer(issuer); - - if (validConditions) { - response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5)); - - } - - return Saml2Utils.signSamlObject(response, credential, true); - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java new file mode 100644 index 00000000..5ea7b59b --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java @@ -0,0 +1,371 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthCredentialProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider.IdAustriaClientAuthMetadataProvider; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.RegisterSearchService; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveMobilePhoneSignatureResponseTask; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyOA; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.test.dummy.DummyPendingRequest; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.PvpMetadataResolverFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnResponseValidationException; +import net.shibboleth.utilities.java.support.xml.ParserPool; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.MarshallingException; +import org.opensaml.core.xml.util.XMLObjectSupport; +import org.opensaml.saml.saml2.core.Issuer; +import org.opensaml.saml.saml2.core.Response; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.xml.transform.TransformerException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Objects; + +import static org.junit.Assert.*; +import static org.springframework.util.Assert.isInstanceOf; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" +}) +public class ReceiveMobilePhoneSignatureResponseTaskTest { + + private static final String METADATA_PATH = "classpath:/data/idp_metadata_classpath_entity.xml"; + + @Autowired + protected MsConnectorDummyConfigMap authConfig; + @Autowired + private IdAustriaClientAuthMetadataProvider metadataProvider; + @Autowired + private IdAustriaClientAuthCredentialProvider credentialProvider; + @Autowired + private PvpMetadataResolverFactory metadataFactory; + @Autowired + private ReceiveMobilePhoneSignatureResponseTask task; + + private final ExecutionContext executionContext = new ExecutionContextImpl(); + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private DummyPendingRequest pendingReq; + + /** + * JUnit class initializer. + * + * @throws Exception In case of an OpenSAML3 initialization error + */ + @BeforeClass + public static void initialize() throws Exception { + EaafOpenSaml3xInitializer.eaafInitialize(); + } + + /** + * jUnit test set-up. + * + * @throws Exception In case of an set-up error + */ + @Before + public void setUp() throws Exception { + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpReq.setScheme("https"); + httpReq.setServerPort(443); + httpReq.setContextPath("/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, METADATA_PATH); + + DummyOA oaParam = new DummyOA(); + oaParam.setUniqueAppId("http://test.com/test"); + oaParam.setTargetIdentifier(EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2)); + + pendingReq = new DummyPendingRequest(); + pendingReq.initialize(httpReq, authConfig); + pendingReq.setPendingRequestId(RandomStringUtils.randomAlphanumeric(10)); + pendingReq.setOnlineApplicationConfiguration(oaParam); + + metadataProvider.fullyDestroy(); + } + + @Test + public void unsupportedHttpMethod() { + httpReq = new MockHttpServletRequest("PUT", "https://localhost/authhandler"); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.03", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpGetNoMessage() { + httpReq = new MockHttpServletRequest("GET", "https://localhost/authhandler"); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + + @Test + public void httpPostNoMessage() { + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostMessageNotSigned() throws IOException { + byte[] bytes = IOUtils.toByteArray(ReceiveMobilePhoneSignatureResponseTask.class + .getResourceAsStream("/data/Response_without_sig_classpath_entityid.xml")); + httpReq.addParameter("SAMLResponse", Base64.getEncoder().encodeToString(bytes)); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + + @Test + public void httpPostMessageWrongDestinationEndpoint() throws Exception { + initResponse("/data/Response_with_wrong_destination_endpoint.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((AuthnResponseValidationException) e.getOriginalException()).getErrorId()); + + } + + @Test + public void httpPostValidSignedNoMetadata() throws Exception { + initResponse("/data/Response_without_sig_classpath_entityid.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.11", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionOutDated() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_classpath_entityid.xml", false); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionFromWrongIdp() throws Exception { + authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, + "http://wrong.idp/" + RandomStringUtils.randomAlphabetic(5)); + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_classpath_entityid.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.08", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionMissingAttributes() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_classpath_entityid.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.12", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedWithError() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedWitUserStopErrorCode() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error_userstop.xml", true); + + task.execute(pendingReq, executionContext); + + assertTrue("process not cancelled", executionContext.isProcessCancelled()); + assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); + assertFalse("should not authenticated", pendingReq.isAuthenticated()); + } + + @Test + public void httpPostValidSignedWithErrorAndNoSubCode() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error_without_subcode.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedWithErrorAndEmptySubCode() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_without_sig_with_error_empty_subcode.xml", true); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + assertEquals("sp.pvp2.05", ((EaafException) e.getOriginalException()).getErrorId()); + } + + @Test + public void httpPostValidSignedAssertionEidValidButNameMismatch() throws Exception { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_with_EID.xml", true); + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + eidData.setFamilyName(eidData.getFamilyName() + "notmatching"); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(AuthnResponseValidationException.class, e.getOriginalException()); + isInstanceOf(InvalidUserInputException.class, e.getOriginalException().getCause()); + } + + @Test + public void httpPostValidSignedAssertionEidValid() throws Exception { + // klar darstellen: was ist input, was ist dann expected output ... eigentlich für alle tasks! + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + initResponse("/data/Response_with_EID.xml", true); + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + + task.execute(pendingReq, executionContext); + + AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); + assertEquals("LoA", "http://eidas.europa.eu/LoA/low", session.getQaaLevel()); + assertEquals("IssueInstant", "2014-03-05T06:39:51Z", session.getIssueInstantString()); + + //TODO this is the good case + } + + @NotNull + private SimpleEidasData createEidasDataMatchingToSamlResponse() { + // data from "/data/Response_with_EID.xml" + SimpleEidasData result = new SimpleEidasData(); + result.setFamilyName("Mustermann"); + result.setGivenName("Max"); + result.setDateOfBirth("1940-01-01"); + return result; + } + + private void addSamlResponseToHttpReq(Response response) throws TransformerException, IOException, MarshallingException { + String node = DomUtils.serializeNode(XMLObjectSupport.getMarshaller(response).marshall(response)); + String base64encoded = Base64.getEncoder().encodeToString(node.getBytes(StandardCharsets.UTF_8)); + httpReq.addParameter("SAMLResponse", base64encoded); + } + + private void initResponse(String responsePath, boolean validConditions) throws Exception { + InputStream inputStream = ReceiveMobilePhoneSignatureResponseTaskTest.class.getResourceAsStream(responsePath); + ParserPool parserPool = Objects.requireNonNull(XMLObjectProviderRegistrySupport.getParserPool()); + Response response = (Response) XMLObjectSupport.unmarshallFromInputStream(parserPool, inputStream); + response.setIssueInstant(DateTime.now()); + Issuer issuer = Saml2Utils.createSamlObject(Issuer.class); + issuer.setValue("classpath:/data/idp_metadata_classpath_entity.xml"); + response.setIssuer(issuer); + if (validConditions) { + response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.now().plusMinutes(5)); + } + Response signedResponse = Saml2Utils.signSamlObject(response, credentialProvider.getMessageSigningCredential(), true); + addSamlResponseToHttpReq(signedResponse); + } + +} -- cgit v1.2.3 From cdec2bbf39649f0fbe3d1655f5b47f62a5d0bae6 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 25 Feb 2021 08:33:16 +0100 Subject: Prepare for Mockito testing of MobilePhoneSignature task --- .../modules/auth/eidas/v2/test/EidasSignalServletTest.java | 1 - .../tasks/ReceiveMobilePhoneSignatureResponseTaskTest.java | 11 ++++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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..f1987e33 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 @@ -52,7 +52,6 @@ import eu.eidas.specificcommunication.exception.SpecificCommunicationException; @ContextConfiguration(locations = { "/SpringTest-context_tasks_test.xml", "/SpringTest-context_basic_mapConfig.xml"}) -@EnableWebMvc public class EidasSignalServletTest { @Autowired private MsConnectorDummyConfigMap basicConfig; 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 index 5ea7b59b..c180e6f9 100644 --- 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 @@ -2,6 +2,7 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.SimpleEidasData; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.InvalidUserInputException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustriaClientAuthConstants; @@ -31,12 +32,15 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; +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; @@ -49,9 +53,11 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.Collections; import java.util.Objects; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.eq; import static org.springframework.util.Assert.isInstanceOf; @RunWith(SpringJUnit4ClassRunner.class) @@ -73,6 +79,8 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { private PvpMetadataResolverFactory metadataFactory; @Autowired private ReceiveMobilePhoneSignatureResponseTask task; + @MockBean + private RegisterSearchService registerSearchService; private final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; @@ -96,6 +104,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { */ @Before public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); httpReq.setScheme("https"); httpReq.setServerPort(443); @@ -320,13 +329,13 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedAssertionEidValid() throws Exception { - // klar darstellen: was ist input, was ist dann expected output ... eigentlich für alle tasks! metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( METADATA_PATH, null, "jUnit IDP", null)); initResponse("/data/Response_with_EID.xml", true); AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + Mockito.when(registerSearchService.searchWithBpkZp(eq("BF:QVGm48cqcM4UcyhDTNGYmVdrIoY="))).thenReturn(new MergedRegisterSearchResult(Collections.emptyList(), Collections.emptyList())); task.execute(pendingReq, executionContext); -- cgit v1.2.3 From 4c81b6452edfed8821ddcb2e0253fa316acff73f Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 25 Feb 2021 11:47:01 +0100 Subject: Remove dependency to Powermock, everything can be done with Mockito --- .../auth/eidas/v2/test/EidasSignalServletTest.java | 130 ++++++------ .../tasks/CreateIdentityLinkTaskEidNewTest.java | 182 +++++++++-------- .../v2/test/tasks/CreateIdentityLinkTaskTest.java | 186 +++++++++-------- .../test/tasks/ReceiveEidasResponseTaskTest.java | 65 +++--- .../auth/eidas/v2/test/utils/JoseUtilsTest.java | 55 +++-- .../validation/EidasResponseValidatorTest.java | 221 ++++++++++----------- 6 files changed, 412 insertions(+), 427 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 f1987e33..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,7 +46,6 @@ 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", @@ -60,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. */ @@ -77,7 +75,7 @@ public class EidasSignalServletTest { httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - + final Map spConfig = new HashMap<>(); spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); @@ -91,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)) @@ -144,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)) @@ -182,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)) @@ -218,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/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 2e6790c5..c29c82c7 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; @@ -28,7 +28,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; @@ -80,7 +79,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", @@ -117,9 +115,9 @@ public class CreateIdentityLinkTaskEidNewTest { AlgorithmIdentifiers.RSA_PSS_USING_SHA512)); private static ObjectMapper mapper = new ObjectMapper(); - + private AuthenticationResponse response; - + @Rule public final SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -133,9 +131,9 @@ public class CreateIdentityLinkTaskEidNewTest { httpResp = new MockHttpServletResponse(); RequestContextHolder.resetRequestAttributes(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - + basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false"); - + final Map spConfig = new HashMap<>(); spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); @@ -147,13 +145,13 @@ public class CreateIdentityLinkTaskEidNewTest { pendingReq.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - + pendingReq.setSpConfig(oaParam); pendingReq.setPendingReqId(at.gv.egiz.eaaf.core.impl.utils.Random.nextProcessReferenceValue()); pendingReq.setAuthUrl("http://test.com/"); 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); @@ -166,26 +164,26 @@ public class CreateIdentityLinkTaskEidNewTest { response = buildDummyAuthResponse(true); pendingReq.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - + 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 +191,16 @@ 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(), + 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,59 +208,59 @@ 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()); - - + + // check vsz request ArgumentCaptor argument4 = ArgumentCaptor.forClass(PersonInfoType.class); - ArgumentCaptor argument5 = ArgumentCaptor.forClass(Boolean.class); + ArgumentCaptor 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 argument1 = ArgumentCaptor.forClass(Boolean.class); ArgumentCaptor> argument2 = ArgumentCaptor.forClass(List.class); @@ -270,60 +268,60 @@ public class CreateIdentityLinkTaskEidNewTest { verify(szrMock, times(1)).signContent(argument1.capture(), argument2.capture(), argument3.capture()); Boolean param1 = argument1.getValue(); Assert.assertFalse("addCert flag", param1); - + List 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 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 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 + //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); 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); @@ -331,56 +329,56 @@ 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(), + Assert.assertEquals("LoA", response.getLevelOfAssurance(), authProcessData.getQaaLevel()); - + // check vsz request ArgumentCaptor argument4 = ArgumentCaptor.forClass(PersonInfoType.class); - ArgumentCaptor argument5 = ArgumentCaptor.forClass(Boolean.class); + ArgumentCaptor 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(), @@ -394,8 +392,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(), @@ -442,7 +440,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)); @@ -451,7 +449,7 @@ public class CreateIdentityLinkTaskEidNewTest { if (withAll) { attributeMap.put(attributeDef5, RandomStringUtils.randomAlphabetic(10)); attributeMap.put(attributeDef6, RandomStringUtils.randomAlphabetic(10)); - + } val b = new AuthenticationResponse.Builder(); 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 8c7558dd..4d52566d 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 @@ -18,7 +18,6 @@ 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; @@ -62,7 +61,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", @@ -89,10 +87,10 @@ public class CreateIdentityLinkTaskTest { private TestRequestImpl pendingReq; private DummySpConfiguration oaParam; private SZR szrMock; - + private AuthenticationResponse response; private Map spConfig; - + @Rule public final SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -110,7 +108,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"); @@ -127,34 +125,34 @@ public class CreateIdentityLinkTaskTest { 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 +160,15 @@ 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(), + Assert.assertEquals("LoA", response.getLevelOfAssurance(), authProcessData.getQaaLevel()); - + Assert.assertNotNull("IDL", authProcessData.getIdentityLink()); checkElement("Mustermann", authProcessData.getIdentityLink().getFamilyName()); checkElement("Hans", authProcessData.getIdentityLink().getGivenName()); @@ -178,35 +176,35 @@ 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 buildIdentityLinkWithWbpk() throws Exception { //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 +212,42 @@ 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(), + 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 +255,80 @@ 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(), + 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 +337,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 +363,38 @@ 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(), + 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 +402,17 @@ 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(), + Assert.assertEquals("LoA", response.getLevelOfAssurance(), authProcessData.getQaaLevel()); - + Assert.assertNotNull("IDL", authProcessData.getIdentityLink()); - + } private void setSzrResponseIdentityLink(String responseXmlPath) throws JAXBException, SZRException_Exception { @@ -433,7 +431,7 @@ public class CreateIdentityLinkTaskTest { Assert.assertEquals(expected, value); } - + @NotNull private AuthenticationResponse buildDummyAuthResponse() throws URISyntaxException { final AttributeDefinition attributeDef = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( @@ -444,7 +442,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)) 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/ReceiveEidasResponseTaskTest.java index de9b2d3b..ae3a79b8 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/ReceiveEidasResponseTaskTest.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,7 +47,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", @@ -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. */ @@ -84,7 +81,7 @@ public class ReceiveEidasResponseTaskTest { RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false"); - + final Map spConfig = new HashMap<>(); spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); @@ -98,70 +95,70 @@ 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 AuthProcessDataWrapper authProcessData = storedReq.getSessionData(AuthProcessDataWrapper.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)); - + } - + @NotNull private AuthenticationResponse buildDummyAuthResponse(String statusCode) throws URISyntaxException { final AttributeDefinition attributeDef = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( @@ -172,7 +169,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)) @@ -189,5 +186,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/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 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 = 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 = 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 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 = 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 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/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 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)) -- cgit v1.2.3 From 33b975f1bda7a2838d280d3f080b095d069d6d02 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 25 Feb 2021 09:00:02 +0100 Subject: Test input/output for MobilePhoneSignature task --- ...eceiveMobilePhoneSignatureResponseTaskTest.java | 101 ++++++++++++++++----- 1 file changed, 80 insertions(+), 21 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index c180e6f9..01688214 100644 --- 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 @@ -3,8 +3,10 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; +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; @@ -19,10 +21,12 @@ 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 com.google.common.collect.Lists; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomStringUtils; @@ -54,9 +58,11 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collections; +import java.util.List; import java.util.Objects; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.springframework.util.Assert.isInstanceOf; @@ -68,6 +74,7 @@ import static org.springframework.util.Assert.isInstanceOf; 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; @@ -212,8 +219,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedAssertionOutDated() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_without_sig_classpath_entityid.xml", false); TaskExecutionException e = assertThrows(TaskExecutionException.class, @@ -228,8 +234,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { public void httpPostValidSignedAssertionFromWrongIdp() throws Exception { authConfig.putConfigValue(IdAustriaClientAuthConstants.CONFIG_PROPS_ID_AUSTRIA_ENTITYID, "http://wrong.idp/" + RandomStringUtils.randomAlphabetic(5)); - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_without_sig_classpath_entityid.xml", true); TaskExecutionException e = assertThrows(TaskExecutionException.class, @@ -242,8 +247,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedAssertionMissingAttributes() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_without_sig_classpath_entityid.xml", true); TaskExecutionException e = assertThrows(TaskExecutionException.class, @@ -256,8 +260,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedWithError() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_without_sig_with_error.xml", true); TaskExecutionException e = assertThrows(TaskExecutionException.class, @@ -270,8 +273,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedWitUserStopErrorCode() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_without_sig_with_error_userstop.xml", true); task.execute(pendingReq, executionContext); @@ -283,8 +285,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedWithErrorAndNoSubCode() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_without_sig_with_error_without_subcode.xml", true); TaskExecutionException e = assertThrows(TaskExecutionException.class, @@ -297,8 +298,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedWithErrorAndEmptySubCode() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_without_sig_with_error_empty_subcode.xml", true); TaskExecutionException e = assertThrows(TaskExecutionException.class, @@ -311,8 +311,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { @Test public void httpPostValidSignedAssertionEidValidButNameMismatch() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + setupMetadataResolver(); initResponse("/data/Response_with_EID.xml", true); AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); @@ -328,22 +327,77 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { } @Test - public void httpPostValidSignedAssertionEidValid() throws Exception { - metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( - METADATA_PATH, null, "jUnit IDP", null)); + public void httpPostValidSignedAssertionEidValid_NoRegisterResult() throws Exception { + setupMetadataResolver(); + initResponse("/data/Response_with_EID.xml", true); + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + MergedRegisterSearchResult registerSearchResult = new MergedRegisterSearchResult(Collections.emptyList(), Collections.emptyList()); + Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(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(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - Mockito.when(registerSearchService.searchWithBpkZp(eq("BF:QVGm48cqcM4UcyhDTNGYmVdrIoY="))).thenReturn(new MergedRegisterSearchResult(Collections.emptyList(), Collections.emptyList())); + MergedRegisterSearchResult registerSearchResult = buildResultWithOneMatch(); + Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(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)); + Mockito.verify(registerSearchService).step7aKittProcess(any(), eq(registerSearchResult), eq(eidData), eq(pendingReq)); + } + + @Test + public void httpPostValidSignedAssertionEidValid_MoreThanOneRegisterResult() throws Exception { + setupMetadataResolver(); + initResponse("/data/Response_with_EID.xml", true); + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); + MergedRegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); + Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(registerSearchResult); + + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); - //TODO this is the good case + 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 MergedRegisterSearchResult buildResultWithOneMatch() { + return new MergedRegisterSearchResult(Collections.singletonList(new RegisterResult(BPK_FROM_ID_AUSTRIA, "bar", "foo", "foo", "bar")), Collections.emptyList()); + } + + @NotNull + private MergedRegisterSearchResult buildResultWithTwoMatches() { + List results = Lists.newArrayList(new RegisterResult(BPK_FROM_ID_AUSTRIA, "bar", "foo", "foo", "bar"), + new RegisterResult("bpk", "pseudonym", "givenName", "familyName", "dateOfBirth")); + return new MergedRegisterSearchResult(results, Collections.emptyList()); } @NotNull @@ -377,4 +431,9 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { addSamlResponseToHttpReq(signedResponse); } + private void setupMetadataResolver() throws Pvp2MetadataException { + metadataProvider.addMetadataResolverIntoChain(metadataFactory.createMetadataProvider( + METADATA_PATH, null, "jUnit IDP", null)); + } + } -- cgit v1.2.3 From 8c13c21799beed76eea848504677eb935026397c Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 25 Feb 2021 11:18:44 +0100 Subject: Implement and test ReceiveAustrianResidenceGuiResponseTask --- ...eceiveAustrianResidenceGuiResponseTaskTest.java | 196 +++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAustrianResidenceGuiResponseTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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..38693f49 --- /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,196 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; +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.tasks.ReceiveAustrianResidenceGuiResponseTask; +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 com.google.common.collect.Lists; +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 java.util.Collections; +import java.util.List; + +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask.*; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.springframework.util.Assert.isInstanceOf; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml" +}) +public class ReceiveAustrianResidenceGuiResponseTaskTest { + + @Autowired + protected MsConnectorDummyConfigMap authConfig; + @Autowired + private ReceiveAustrianResidenceGuiResponseTask task; + @MockBean + private RegisterSearchService registerSearchService; + + 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); + + 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(); + MergedRegisterSearchResult registerSearchResult = buildEmptyResult(); + mockRegisterSearch(userInput, 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(); + MergedRegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildMatchingRegisterResult(eidasData)); + mockRegisterSearch(userInput, registerSearchResult); + + task.execute(pendingReq, executionContext); + + assertNull("Transition To S9", executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); + Mockito.verify(registerSearchService).step7aKittProcess(any(), eq(registerSearchResult), eq(eidasData), eq(pendingReq)); + } + + @Test + public void exactlyOneRegisterResult_NotMatching() throws Exception { + UserInput userInput = setupUserInput(); + SimpleEidasData eidasData = setupEidasData(); + MergedRegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildNotMatchingRegisterResult(eidasData)); + mockRegisterSearch(userInput, registerSearchResult); + + 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(); + MergedRegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); + mockRegisterSearch(userInput, registerSearchResult); + + 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, MergedRegisterSearchResult registerSearchResult) { + Mockito.when(registerSearchService.searchWithResidence(eq(userInput.getZipcode()), eq(userInput.getCity()), eq(userInput.getStreet()))).thenReturn(registerSearchResult); + } + + @NotNull + private MergedRegisterSearchResult buildEmptyResult() { + return new MergedRegisterSearchResult(Collections.emptyList(), Collections.emptyList()); + } + + @NotNull + private MergedRegisterSearchResult buildResultWithOneMatch(RegisterResult registerResult) { + return new MergedRegisterSearchResult(Collections.singletonList(registerResult), Collections.emptyList()); + } + + @NotNull + private MergedRegisterSearchResult buildResultWithTwoMatches() { + List results = Lists.newArrayList(buildRandomRegisterResult(), buildRandomRegisterResult()); + return new MergedRegisterSearchResult(results, Collections.emptyList()); + } + + @NotNull + private RegisterResult buildRandomRegisterResult() { + return new RegisterResult(RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8)); + } + + private RegisterResult buildMatchingRegisterResult(SimpleEidasData eidData) { + return new RegisterResult(RandomStringUtils.randomAlphabetic(8), eidData.getPseudonym(), eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth()); + } + + private RegisterResult buildNotMatchingRegisterResult(SimpleEidasData eidData) { + return new RegisterResult(RandomStringUtils.randomAlphabetic(8), eidData.getPseudonym() + RandomStringUtils.randomAlphabetic(8), eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth()); + } + + 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 = new SimpleEidasData(); + result.setPseudonym(RandomStringUtils.randomAlphabetic(8)); + result.setFamilyName(RandomStringUtils.randomAlphabetic(8)); + result.setGivenName(RandomStringUtils.randomAlphabetic(8)); + result.setDateOfBirth("1970-01-01"); + 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; + } + + +} -- cgit v1.2.3 From 2c49670334049a065d86defc8524f2e5eae6ca78 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 25 Feb 2021 11:32:57 +0100 Subject: Refactor and test ReceiveOtherLoginMethodGuiResponse --- ...ReceiveOtherLoginMethodGuiResponseTaskTest.java | 89 ++++++++++++---------- 1 file changed, 47 insertions(+), 42 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index ae4b5d8c..c6b2e1fe 100644 --- 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 @@ -2,12 +2,12 @@ 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.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,16 +23,10 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import java.io.UnsupportedEncodingException; +import static org.junit.Assert.*; +import static org.springframework.util.Assert.isInstanceOf; @RunWith(SpringJUnit4ClassRunner.class) -//@ContextConfiguration({ -// "/applicationContext.xml", -// "/specific_eIDAS_connector.beans.xml", -// "/eaaf_core.beans.xml", -// "/eaaf_pvp.beans.xml", -// "/eaaf_pvp_idp.beans.xml", -// "/spring/SpringTest-context_simple_storage.xml" }) @ContextConfiguration(locations = { "/SpringTest-context_tasks_test.xml", "/SpringTest-context_basic_mapConfig.xml" @@ -41,27 +35,25 @@ import java.io.UnsupportedEncodingException; @WebAppConfiguration public class ReceiveOtherLoginMethodGuiResponseTaskTest { - @Autowired private ReceiveOtherLoginMethodGuiResponseTask task; + @Autowired + private ReceiveOtherLoginMethodGuiResponseTask task; - private ExecutionContextImpl executionContext = new ExecutionContextImpl(); + 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() { @@ -79,57 +71,70 @@ public class ReceiveOtherLoginMethodGuiResponseTaskTest { @Test public void withMobileSignatureSelection() throws TaskExecutionException { - test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); + testTransition(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN, Constants.TRANSITION_TO_GENERATE_MOBILE_PHONE_SIGNATURE_REQUEST_TASK); } @Test public void withEidasSelection() throws TaskExecutionException { - test(SelectedLoginMethod.MOBILE_PHONE_SIGNATURE_LOGIN); + testTransition(SelectedLoginMethod.EIDAS_LOGIN, Constants.TRANSITION_TO_GENERATE_EIDAS_LOGIN); } @Test public void withNoOtherLoginSelection() throws TaskExecutionException { - test(SelectedLoginMethod.NO_OTHER_LOGIN); + testTransition(SelectedLoginMethod.NO_OTHER_LOGIN, Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK); } - public void test(SelectedLoginMethod loginMethod) throws TaskExecutionException { - String parameterValue = loginMethod.name(); - httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); + public void testTransition(SelectedLoginMethod loginMethod, String expectedTransition) throws TaskExecutionException { + httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, loginMethod.name()); task.execute(pendingReq, executionContext); - //result validation - Assert.assertFalse("wrong pendingReq auth flag", pendingReq.isAuthenticated()); - Assert.assertFalse("wrong process-cancelled flag", executionContext.isProcessCancelled()); - - Assert.assertNotNull("no login-selection found", - executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); - Assert.assertEquals("Wrong login-selection found", loginMethod, - executionContext.get(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER)); + 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)); - @Test(expected = TaskExecutionException.class) - public void withInvalidSelection() throws TaskExecutionException { - String parameterValue = RandomStringUtils.randomAlphabetic(2); - httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, parameterValue); - task.execute(pendingReq, executionContext); + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); } - @Test(expected = TaskExecutionException.class) - public void withNullSelection() throws TaskExecutionException { + @Test + public void withNullSelection() { httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, "null"); - task.execute(pendingReq, executionContext); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); } - @Test(expected = TaskExecutionException.class) - public void withEmptySelection() throws TaskExecutionException { + @Test + public void withEmptySelection() { httpReq.setParameter(Constants.REQ_SELECTED_LOGIN_METHOD_PARAMETER, ""); - task.execute(pendingReq, executionContext); + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); } - @Test(expected = TaskExecutionException.class) - public void withoutLoginMethodSelection() throws TaskExecutionException, UnsupportedEncodingException { - task.execute(pendingReq, executionContext); + @Test + public void withoutLoginMethodSelection() { + + TaskExecutionException e = assertThrows(TaskExecutionException.class, + () -> task.execute(pendingReq, executionContext)); + + assertEquals(pendingReq.getPendingRequestId(), e.getPendingRequestID()); + isInstanceOf(InvalidUserInputException.class, e.getOriginalException()); } } -- cgit v1.2.3 From c5d36685c294a383baecf4e12aaeda5be1f13529 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 14:32:20 +0100 Subject: Refactor ErnpData to make it immutable --- .../modules/auth/eidas/v2/test/SzrClientTest.java | 60 +++++++++++----------- .../eidas/v2/test/SzrClientTestProduction.java | 36 ++++++------- .../EidasAttributePostProcessingTest.java | 24 ++++----- 3 files changed, 60 insertions(+), 60 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index cf4ed95c..208a008b 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -67,7 +67,7 @@ import com.skjolberg.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.dao.ErnpEidData; 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; @@ -103,7 +103,7 @@ public class SzrClientTest { @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"; @@ -111,7 +111,7 @@ public class SzrClientTest { private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; private SZR szrMock = null; - ErnbEidData eidData = null; + ErnpEidData eidData = null; @Rule public SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -125,16 +125,16 @@ public class SzrClientTest { 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"); - + + eidData = ErnpEidData.builder() + .familyName(familyName) + .givenName(givenName) + .dateOfBirth(new DateTime()) + .citizenCountryCode("IS") + .pseudonym("1234sdgsdfg56789ABCDEF").build(); + basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.eidasbind.mds.inject", "false"); - + } @@ -181,40 +181,40 @@ public class SzrClientTest { 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); } 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); } 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(); @@ -222,19 +222,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); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); - - } + + } } - + @Test - public void eidasBindValid() throws SZRException_Exception, SzrCommunicationException, JsonMappingException, + public void eidasBindValid() throws SZRException_Exception, SzrCommunicationException, JsonMappingException, JsonProcessingException, JoseException { final SignContentResponse szrResponse = new SignContentResponse(); final SignContentEntry result1 = new SignContentEntry(); @@ -253,14 +253,14 @@ public class SzrClientTest { Assert.assertNotNull("bcBind is null", bcBind); Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); - + } @Test - public void eidasBindValidWithMds() throws SZRException_Exception, SzrCommunicationException, JoseException, + public void eidasBindValidWithMds() throws SZRException_Exception, SzrCommunicationException, JoseException, JsonMappingException, JsonProcessingException { 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(); @@ -280,7 +280,7 @@ public class SzrClientTest { Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); } - + @Test public void getIdentityLinkRawModeValidResponse() throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index 1e7ff369..eff56ffd 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -48,7 +48,7 @@ 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.dao.ErnpEidData; 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; @@ -98,32 +98,32 @@ public class SzrClientTestProduction { } @Test - public void getVsz() throws SzrCommunicationException, EidasSAuthenticationException { - String vsz = szrClient.getEncryptedStammzahl(getPersonInfo()); + public void getVsz() throws SzrCommunicationException, EidasSAuthenticationException { + String vsz = szrClient.getEncryptedStammzahl(getPersonInfo()); Assert.assertNotNull("vsz", vsz); - + } @Test - public void getEidasBind() throws SzrCommunicationException, EidasSAuthenticationException { + public void getEidasBind() throws SzrCommunicationException, 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); - + ErnpEidData eidData = ErnpEidData.builder() + .familyName(familyName) + .givenName(givenName) + .dateOfBirth(new DateTime()) + .citizenCountryCode("IS") + .pseudonym("1234sdgsdfg56789ABCDEF").build(); + + + String eidasBind = szrClient.getEidsaBind(vsz, bindingPubKey, eidStatus, eidData); + Assert.assertNotNull("eidasBind", eidasBind); - + } - - + + @Test public void getIdentityLinkRawMode() throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, EidasSAuthenticationException { 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..381406d2 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 @@ -41,7 +41,7 @@ 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.dao.ErnpEidData; import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.CcSpecificEidProcessingService; @RunWith(SpringJUnit4ClassRunner.class) @@ -116,7 +116,7 @@ public class EidasAttributePostProcessingTest { /** * jUnit class initializer. - * + * * @throws IOException In case of an error */ @BeforeClass @@ -129,7 +129,7 @@ public class EidasAttributePostProcessingTest { @Test public void deWithHexLowerCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( P1_eIDASID, P1_FAMILYNAME, @@ -156,7 +156,7 @@ public class EidasAttributePostProcessingTest { @Test public void deWithHexMixedCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( P3_eIDASID, P3_FAMILYNAME, @@ -183,7 +183,7 @@ public class EidasAttributePostProcessingTest { @Test public void deWithHexUpperCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( P4_eIDASID, P4_FAMILYNAME, @@ -270,7 +270,7 @@ public class EidasAttributePostProcessingTest { @Test public void eeTestCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( P2_eIDASID, P2_FAMILYNAME, @@ -297,7 +297,7 @@ public class EidasAttributePostProcessingTest { @Test public void eeTestFamilyNameMissingCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( P2_eIDASID, null, @@ -326,7 +326,7 @@ public class EidasAttributePostProcessingTest { @Test public void eeTestGivenNameMissingCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( P2_eIDASID, P2_FAMILYNAME, @@ -355,7 +355,7 @@ public class EidasAttributePostProcessingTest { @Test public void eeTestDateOfBirthMissingCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( P2_eIDASID, P2_FAMILYNAME, @@ -384,7 +384,7 @@ public class EidasAttributePostProcessingTest { @Test public void eeTestIdMissingCase() throws Exception { try { - final ErnbEidData result = postProcessor.postProcess( + final ErnpEidData result = postProcessor.postProcess( generateInputData( null, P2_FAMILYNAME, @@ -423,8 +423,8 @@ public class EidasAttributePostProcessingTest { } - private void validate(ErnbEidData result, String id, String familyName, String givenName, - DateTime dateOfBirth, String placeOfBirth, String birthName) { + private void validate(ErnpEidData result, String id, String familyName, String givenName, + DateTime dateOfBirth, String placeOfBirth, String birthName) { if (!result.getPseudonym().equals(id)) { fail(result.getPseudonym() + "is not equal to " + id); } -- cgit v1.2.3 From 20fcdf7cd830af9f23645c71f536af95418ad1be Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 15:04:08 +0100 Subject: Refactor SimpleEidasData to make it immutable --- ...eceiveAustrianResidenceGuiResponseTaskTest.java | 11 ++++++----- ...eceiveMobilePhoneSignatureResponseTaskTest.java | 23 +++++++++++----------- 2 files changed, 17 insertions(+), 17 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index 38693f49..d9405251 100644 --- 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 @@ -175,11 +175,12 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { @NotNull private SimpleEidasData setupEidasData() throws EaafStorageException { - SimpleEidasData result = new SimpleEidasData(); - result.setPseudonym(RandomStringUtils.randomAlphabetic(8)); - result.setFamilyName(RandomStringUtils.randomAlphabetic(8)); - result.setGivenName(RandomStringUtils.randomAlphabetic(8)); - result.setDateOfBirth("1970-01-01"); + 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; 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 index 01688214..77b87264 100644 --- 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 @@ -314,8 +314,9 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { setupMetadataResolver(); initResponse("/data/Response_with_EID.xml", true); AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); - eidData.setFamilyName(eidData.getFamilyName() + "notmatching"); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse() + .familyName("notmatching") + .build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); TaskExecutionException e = assertThrows(TaskExecutionException.class, @@ -331,7 +332,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { setupMetadataResolver(); initResponse("/data/Response_with_EID.xml", true); AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); MergedRegisterSearchResult registerSearchResult = new MergedRegisterSearchResult(Collections.emptyList(), Collections.emptyList()); Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(registerSearchResult); @@ -350,7 +351,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { setupMetadataResolver(); initResponse("/data/Response_with_EID.xml", true); AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); MergedRegisterSearchResult registerSearchResult = buildResultWithOneMatch(); Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(registerSearchResult); @@ -370,7 +371,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { setupMetadataResolver(); initResponse("/data/Response_with_EID.xml", true); AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - SimpleEidasData eidData = createEidasDataMatchingToSamlResponse(); + SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); MergedRegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(registerSearchResult); @@ -400,14 +401,12 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { return new MergedRegisterSearchResult(results, Collections.emptyList()); } - @NotNull - private SimpleEidasData createEidasDataMatchingToSamlResponse() { + private SimpleEidasData.SimpleEidasDataBuilder createEidasDataMatchingToSamlResponse() { // data from "/data/Response_with_EID.xml" - SimpleEidasData result = new SimpleEidasData(); - result.setFamilyName("Mustermann"); - result.setGivenName("Max"); - result.setDateOfBirth("1940-01-01"); - return result; + return SimpleEidasData.builder() + .familyName("Mustermann") + .givenName("Max") + .dateOfBirth("1940-01-01"); } private void addSamlResponseToHttpReq(Response response) throws TransformerException, IOException, MarshallingException { -- cgit v1.2.3 From ac1fbd5854cc38f6efb32b3baf7cb7cac083e3b3 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 15:23:24 +0100 Subject: Refactor CreateIdentityLinkTask for more readability --- .../specific/modules/auth/eidas/v2/test/SzrClientTest.java | 12 ++++++------ .../modules/auth/eidas/v2/test/SzrClientTestProduction.java | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index 208a008b..99c221d8 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -176,7 +176,7 @@ public class SzrClientTest { when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); final String bcBind = szrClient - .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), eidData); Assert.assertNotNull("bcBind is null", bcBind); @@ -190,7 +190,7 @@ public class SzrClientTest { try { szrClient - .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), eidData); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); @@ -207,7 +207,7 @@ public class SzrClientTest { try { szrClient - .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), eidData); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); @@ -225,7 +225,7 @@ public class SzrClientTest { try { szrClient - .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), eidData); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); @@ -248,7 +248,7 @@ public class SzrClientTest { when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); final String bcBind = szrClient - .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), eidData); Assert.assertNotNull("bcBind is null", bcBind); @@ -273,7 +273,7 @@ public class SzrClientTest { when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); final String bcBind = szrClient - .getEidsaBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), + .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), eidData); Assert.assertNotNull("bcBind is null", bcBind); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index eff56ffd..abebf0da 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -117,7 +117,7 @@ public class SzrClientTestProduction { .pseudonym("1234sdgsdfg56789ABCDEF").build(); - String eidasBind = szrClient.getEidsaBind(vsz, bindingPubKey, eidStatus, eidData); + String eidasBind = szrClient.getEidasBind(vsz, bindingPubKey, eidStatus, eidData); Assert.assertNotNull("eidasBind", eidasBind); -- cgit v1.2.3 From 1bb05a848206fb1e3bd77b744068c1ee5b344d73 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 16:02:22 +0100 Subject: Prevent SZRClient from creating ERnP entry if person does not exist --- .../modules/auth/eidas/v2/test/SzrClientTest.java | 39 +++++++++------------- .../eidas/v2/test/SzrClientTestProduction.java | 22 +++++------- .../tasks/CreateIdentityLinkTaskEidNewTest.java | 4 +-- 3 files changed, 27 insertions(+), 38 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index 99c221d8..5deb5f31 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -28,10 +28,10 @@ import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.when; import java.io.IOException; -import java.security.InvalidKeyException; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchProviderException; import java.util.List; +import java.util.Objects; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @@ -44,7 +44,6 @@ 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; @@ -60,9 +59,6 @@ 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.skjolberg.mockito.soap.SoapServiceRule; import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; @@ -102,8 +98,6 @@ public class SzrClientTest { @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"; @@ -139,7 +133,7 @@ public class SzrClientTest { @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); @@ -156,7 +150,7 @@ public class SzrClientTest { when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(null); try { - stammzahlEncrypted = szrClient.getEncryptedStammzahl(new PersonInfoType()); + szrClient.getEncryptedStammzahl(new PersonInfoType()); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); } @@ -234,8 +228,7 @@ public class SzrClientTest { } @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(); @@ -257,8 +250,7 @@ public class SzrClientTest { } @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(); @@ -283,7 +275,7 @@ public class SzrClientTest { @Test public void getIdentityLinkRawModeValidResponse() - throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, + throws SZRException_Exception, EaafParserException, EidasSAuthenticationException, JAXBException { setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml"); @@ -317,8 +309,8 @@ public class SzrClientTest { @Test public void getIdentityLinkRawModeErrorTravelerDocExists() - throws SZRException_Exception, EaafParserException, NoSuchProviderException, IOException, InvalidKeyException, - EidasSAuthenticationException, JAXBException, ParserConfigurationException, SAXException { + throws SZRException_Exception, IOException, + EidasSAuthenticationException, ParserConfigurationException, SAXException { setSzrExceptionIdentityLink("/data/szr/szr_resp_error_travelerdocexists.xml"); try { @@ -342,7 +334,7 @@ public class SzrClientTest { @Ignore @Test - public void getBpkTest() throws SZRException_Exception, EidasSAuthenticationException { + public void getBpkTest() throws EidasSAuthenticationException { final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, basicConfig .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")); @@ -363,6 +355,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, @@ -375,8 +368,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( @@ -391,9 +385,8 @@ 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; + final byte[] hash = md.digest(uniqueId.getBytes(StandardCharsets.UTF_8)); + return new String(Base64Utils.encode(hash), StandardCharsets.UTF_8).replaceAll("\r\n", ""); } catch (final Exception ex) { throw new EidasSAuthenticationException("internal.03", new Object[]{}, ex); @@ -413,7 +406,7 @@ public class SzrClientTest { // parse some eID attributes final Triple eIdentifier = EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); - final String uniqueId = createHashFromUniqueId(eIdentifier.getThird()); + final String uniqueId = createHashFromUniqueId(Objects.requireNonNull(eIdentifier).getThird()); final String citizenCountry = eIdentifier.getFirst(); // person information diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index abebf0da..38829d67 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -23,11 +23,10 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; -import java.io.IOException; -import java.security.InvalidKeyException; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchProviderException; import java.util.List; +import java.util.Objects; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; @@ -63,7 +62,6 @@ 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; @@ -98,14 +96,14 @@ public class SzrClientTestProduction { } @Test - public void getVsz() throws SzrCommunicationException, EidasSAuthenticationException { + public void getVsz() throws EidasSAuthenticationException { String vsz = szrClient.getEncryptedStammzahl(getPersonInfo()); 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"; @@ -125,8 +123,7 @@ public class SzrClientTestProduction { @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()); @@ -173,7 +170,7 @@ public class SzrClientTestProduction { @Ignore @Test - public void getBpkTest() throws SZRException_Exception, EidasSAuthenticationException { + public void getBpkTest() throws EidasSAuthenticationException { final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, basicConfig.getBasicConfiguration( Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, @@ -193,9 +190,8 @@ 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; + final byte[] hash = md.digest(uniqueId.getBytes(StandardCharsets.UTF_8)); + return new String(Base64Utils.encode(hash), StandardCharsets.UTF_8).replaceAll("\r\n", ""); } catch (final Exception ex) { throw new EidasSAuthenticationException("internal.03", new Object[] {}, ex); @@ -216,7 +212,7 @@ public class SzrClientTestProduction { // parse some eID attributes final Triple eIdentifier = EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); - final String uniqueId = createHashFromUniqueId(eIdentifier.getThird()); + final String uniqueId = createHashFromUniqueId(Objects.requireNonNull(eIdentifier).getThird()); final String citizenCountry = eIdentifier.getFirst(); // person information 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 c29c82c7..ee7d2ebd 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 @@ -227,7 +227,7 @@ public class CreateIdentityLinkTaskEidNewTest { verify(szrMock, times(1)).getStammzahlEncrypted(argument4.capture(), argument5.capture()); Boolean param5 = argument5.getValue(); - Assert.assertTrue("insertERnP flag", param5); + Assert.assertFalse("insertERnP flag", param5); PersonInfoType person = argument4.getValue(); Assert.assertEquals("FamilyName", response.getAttributes().getAttributeValuesByFriendlyName("FamilyName").getFirstValue( @@ -344,7 +344,7 @@ public class CreateIdentityLinkTaskEidNewTest { verify(szrMock, times(1)).getStammzahlEncrypted(argument4.capture(), argument5.capture()); Boolean param5 = argument5.getValue(); - Assert.assertTrue("insertERnP flag", param5); + Assert.assertFalse("insertERnP flag", param5); PersonInfoType person = argument4.getValue(); Assert.assertEquals("FamilyName", response.getAttributes().getAttributeValuesByFriendlyName("FamilyName").getFirstValue( -- cgit v1.2.3 From 7e638d692540f83c35184b4d2629ea85ee051845 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 16:53:04 +0100 Subject: Remove setting QAA level from CreateIdentityLink This is already set in ReceiveAuthnResponse --- .../v2/test/tasks/CreateIdentityLinkTaskEidNewTest.java | 7 ------- .../eidas/v2/test/tasks/CreateIdentityLinkTaskTest.java | 15 --------------- 2 files changed, 22 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 ee7d2ebd..248b71d9 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 @@ -196,10 +196,6 @@ public class CreateIdentityLinkTaskEidNewTest { Assert.assertTrue("foreigner process", authProcessData.isForeigner()); 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, @@ -334,9 +330,6 @@ public class CreateIdentityLinkTaskEidNewTest { Assert.assertTrue("foreigner process", authProcessData.isForeigner()); 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 argument4 = ArgumentCaptor.forClass(PersonInfoType.class); 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 4d52566d..556bd2eb 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 @@ -165,9 +165,6 @@ public class CreateIdentityLinkTaskTest { Assert.assertTrue("foreigner process", authProcessData.isForeigner()); 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()); @@ -217,9 +214,6 @@ public class CreateIdentityLinkTaskTest { Assert.assertTrue("foreigner process", authProcessData.isForeigner()); 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=", @@ -260,9 +254,6 @@ public class CreateIdentityLinkTaskTest { Assert.assertTrue("foreigner process", authProcessData.isForeigner()); 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()); @@ -368,9 +359,6 @@ public class CreateIdentityLinkTaskTest { Assert.assertTrue("foreigner process", authProcessData.isForeigner()); 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, @@ -407,9 +395,6 @@ public class CreateIdentityLinkTaskTest { Assert.assertTrue("foreigner process", authProcessData.isForeigner()); 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()); -- cgit v1.2.3 From 7e446e645091e0d507222333def540e9c570983c Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 17:12:53 +0100 Subject: Move creating request objects into SzrClient --- .../modules/auth/eidas/v2/test/SzrClientTest.java | 162 ++++++--------------- .../eidas/v2/test/SzrClientTestProduction.java | 110 ++++---------- 2 files changed, 71 insertions(+), 201 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index 5deb5f31..d8f2e47f 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -23,70 +23,45 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.List; -import java.util.Objects; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.ws.soap.SOAPFaultException; - +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.ErnpEidData; +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.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.idp.auth.data.SimpleIdentityLinkAssertionParser; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import com.skjolberg.mockito.soap.SoapServiceRule; 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.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.junit.*; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; 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 szrservices.*; -import com.skjolberg.mockito.soap.SoapServiceRule; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.ws.soap.SOAPFaultException; +import java.io.IOException; +import java.util.List; -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.ErnpEidData; -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 szrservices.GetBPKFromStammzahlEncryptedResponse; -import szrservices.GetBPKFromStammzahlEncryptedResponseType; -import szrservices.GetIdentityLinkEidasResponse; -import szrservices.IdentityLinkType; -import szrservices.PersonInfoType; -import szrservices.SZR; -import szrservices.SZRException_Exception; -import szrservices.SignContentEntry; -import szrservices.SignContentResponse; -import szrservices.SignContentResponseType; -import szrservices.TravelDocumentType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.when; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { @@ -98,14 +73,9 @@ public class SzrClientTest { @Autowired SzrClient szrClient; @Autowired MsConnectorDummyConfigMap 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 eIDASeID = "IS/AT/1234sdgsdfg56789ABCDEF"; private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; private SZR szrMock = null; - ErnpEidData eidData = null; @Rule public SoapServiceRule soap = SoapServiceRule.newInstance(); @@ -117,18 +87,9 @@ public class SzrClientTest { public void initializer() { if (szrMock == null) { szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); - } - eidData = ErnpEidData.builder() - .familyName(familyName) - .givenName(givenName) - .dateOfBirth(new DateTime()) - .citizenCountryCode("IS") - .pseudonym("1234sdgsdfg56789ABCDEF").build(); - basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.eidasbind.mds.inject", "false"); - } @@ -144,13 +105,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 { - szrClient.getEncryptedStammzahl(new PersonInfoType()); + szrClient.getEncryptedStammzahl(getEidData()); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); } @@ -171,7 +132,7 @@ public class SzrClientTest { final String bcBind = szrClient .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), eidData); + RandomStringUtils.randomAlphabetic(10), getEidData()); Assert.assertNotNull("bcBind is null", bcBind); Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); @@ -185,7 +146,7 @@ public class SzrClientTest { try { szrClient .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), eidData); + RandomStringUtils.randomAlphabetic(10), getEidData()); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); @@ -202,7 +163,7 @@ public class SzrClientTest { try { szrClient .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), eidData); + RandomStringUtils.randomAlphabetic(10), getEidData()); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); @@ -220,7 +181,7 @@ public class SzrClientTest { try { szrClient .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), eidData); + RandomStringUtils.randomAlphabetic(10), getEidData()); } catch (SzrCommunicationException e) { Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); @@ -242,7 +203,7 @@ public class SzrClientTest { final String bcBind = szrClient .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), eidData); + RandomStringUtils.randomAlphabetic(10), getEidData()); Assert.assertNotNull("bcBind is null", bcBind); Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); @@ -266,7 +227,7 @@ public class SzrClientTest { final String bcBind = szrClient .getEidasBind(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), eidData); + RandomStringUtils.randomAlphabetic(10), getEidData()); Assert.assertNotNull("bcBind is null", bcBind); Assert.assertEquals("bcBind not match", result1.getValue(), bcBind); @@ -275,13 +236,12 @@ public class SzrClientTest { @Test public void getIdentityLinkRawModeValidResponse() - throws SZRException_Exception, EaafParserException, - 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()); @@ -309,13 +269,12 @@ public class SzrClientTest { @Test public void getIdentityLinkRawModeErrorTravelerDocExists() - throws SZRException_Exception, IOException, - EidasSAuthenticationException, 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) { @@ -335,7 +294,7 @@ public class SzrClientTest { @Ignore @Test public void getBpkTest() throws EidasSAuthenticationException { - final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, basicConfig + final List bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, basicConfig .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")); if (bPK.isEmpty()) { @@ -382,46 +341,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(StandardCharsets.UTF_8)); - return new String(Base64Utils.encode(hash), StandardCharsets.UTF_8).replaceAll("\r\n", ""); - - } catch (final Exception ex) { - throw new EidasSAuthenticationException("internal.03", new Object[]{}, ex); - - } + private ErnpEidData getEidData() { + return ErnpEidData.builder() + .familyName("Mustermann") + .givenName("Franz") + .dateOfBirth(new DateTime(1989,5,5,1,1)) + .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 eIdentifier = EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); - final String uniqueId = createHashFromUniqueId(Objects.requireNonNull(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/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index 38829d67..33d72a59 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -23,11 +23,16 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.List; -import java.util.Objects; - +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.ErnpEidData; +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.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; @@ -43,26 +48,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.ErnpEidData; -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.TravelDocumentType; + +import java.util.List; @IfProfileValue(name = "spring.profiles.active", value = "devEnvironment") @@ -82,12 +71,6 @@ public class SzrClientTestProduction { @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 @@ -97,7 +80,7 @@ public class SzrClientTestProduction { @Test public void getVsz() throws EidasSAuthenticationException { - String vsz = szrClient.getEncryptedStammzahl(getPersonInfo()); + String vsz = szrClient.getEncryptedStammzahl(getEidData()); Assert.assertNotNull("vsz", vsz); } @@ -107,15 +90,8 @@ public class SzrClientTestProduction { String vsz = RandomStringUtils.randomAlphanumeric(10); String bindingPubKey = Base64.toBase64String(RandomStringUtils.random(20).getBytes()); String eidStatus = "urn:eidgvat:eid.status.eidas"; - ErnpEidData eidData = ErnpEidData.builder() - .familyName(familyName) - .givenName(givenName) - .dateOfBirth(new DateTime()) - .citizenCountryCode("IS") - .pseudonym("1234sdgsdfg56789ABCDEF").build(); - - String eidasBind = szrClient.getEidasBind(vsz, bindingPubKey, eidStatus, eidData); + String eidasBind = szrClient.getEidasBind(vsz, bindingPubKey, eidStatus, getEidData()); Assert.assertNotNull("eidasBind", eidasBind); @@ -125,8 +101,7 @@ public class SzrClientTestProduction { @Test 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(); @@ -171,10 +146,9 @@ public class SzrClientTestProduction { @Ignore @Test public void getBpkTest() throws EidasSAuthenticationException { - final List bPK = szrClient.getBpk(getPersonInfo(), DUMMY_TARGET, - basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, - "no VKZ defined")); + String vkz = basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined"); + final List bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, vkz); if (bPK.isEmpty()) { throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); @@ -187,46 +161,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(StandardCharsets.UTF_8)); - return new String(Base64Utils.encode(hash), StandardCharsets.UTF_8).replaceAll("\r\n", ""); - - } catch (final Exception ex) { - throw new EidasSAuthenticationException("internal.03", new Object[] {}, ex); - - } + private ErnpEidData getEidData() { + return ErnpEidData.builder() + .familyName("Mustermann") + .givenName("Franz") + .dateOfBirth(new DateTime(1989,5,4,1,1)) + .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 eIdentifier = - EidasResponseUtils.parseEidasPersonalIdentifier(eIDASeID); - final String uniqueId = createHashFromUniqueId(Objects.requireNonNull(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; - } } -- cgit v1.2.3 From 9df463ce8c8567a8f70c4f8f1988f5ae299b6369 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 17:29:03 +0100 Subject: Replace ErnpEidData with SimpleEidasData --- .../modules/auth/eidas/v2/test/SzrClientTest.java | 9 ++--- .../eidas/v2/test/SzrClientTestProduction.java | 9 ++--- .../EidasAttributePostProcessingTest.java | 45 +++++++++------------- 3 files changed, 27 insertions(+), 36 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index d8f2e47f..d861006e 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -25,7 +25,7 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; 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.ErnpEidData; +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; @@ -39,7 +39,6 @@ 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.junit.*; import org.junit.runner.RunWith; import org.slf4j.Logger; @@ -341,11 +340,11 @@ public class SzrClientTest { } - private ErnpEidData getEidData() { - return ErnpEidData.builder() + private SimpleEidasData getEidData() { + return SimpleEidasData.builder() .familyName("Mustermann") .givenName("Franz") - .dateOfBirth(new DateTime(1989,5,5,1,1)) + .dateOfBirth("1989-05-05") .citizenCountryCode("IS") .pseudonym("1234sdgsdfg56789ABCDEF") .build(); diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index 33d72a59..e50044c6 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -24,7 +24,7 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.ErnpEidData; +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; @@ -36,7 +36,6 @@ 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; @@ -161,11 +160,11 @@ public class SzrClientTestProduction { } - private ErnpEidData getEidData() { - return ErnpEidData.builder() + private SimpleEidasData getEidData() { + return SimpleEidasData.builder() .familyName("Mustermann") .givenName("Franz") - .dateOfBirth(new DateTime(1989,5,4,1,1)) + .dateOfBirth("1989-05-04") .citizenCountryCode("IS") .pseudonym("1234ffgsdfg56789ABCDEF") .build(); 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 381406d2..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.ErnpEidData; 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,7 +109,7 @@ 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"; @@ -129,7 +128,7 @@ public class EidasAttributePostProcessingTest { @Test public void deWithHexLowerCase() throws Exception { try { - final ErnpEidData 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 ErnpEidData 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 ErnpEidData 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 ErnpEidData 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 ErnpEidData 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 ErnpEidData 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 ErnpEidData 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 ErnpEidData result = postProcessor.postProcess( + final SimpleEidasData result = postProcessor.postProcess( generateInputData( null, P2_FAMILYNAME, @@ -411,7 +410,7 @@ public class EidasAttributePostProcessingTest { } private Map generateInputData(String id, String familyName, String givenName, - DateTime dateOfBirth, String placeOfBirth, String birthName) { + String dateOfBirth, String placeOfBirth, String birthName) { final Map 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(ErnpEidData 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); } -- cgit v1.2.3 From 27f2e48e6a585e2d1462b60214b5cfcd8f40680b Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Thu, 4 Mar 2021 17:47:41 +0100 Subject: Copy post processing eIDAS attributes to InitialSearchTask --- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 37 +++++++++++++++++++--- 1 file changed, 32 insertions(+), 5 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index c9f123dc..643afb90 100644 --- 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 @@ -25,13 +25,19 @@ 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.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.EidPostProcessingException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasAttributeException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.GenericEidProcessor; import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.ItSpecificDetailSearchProcessor; +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.tasks.InitialSearchTask; import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; +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; @@ -41,6 +47,7 @@ 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; @@ -65,6 +72,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; +import java.util.Map; import java.util.Random; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; @@ -86,6 +94,7 @@ public class InitialSearchTaskTest { private IZmrClient zmrClient; @Mock private IErnpClient ernpClient; + private final ICcSpecificEidProcessingService eidPostProcessor = createEidPostProcessor(); private RegisterSearchService registerSearchService; final ExecutionContext executionContext = new ExecutionContextImpl(); @@ -106,7 +115,7 @@ public class InitialSearchTaskTest { public void setUp() throws URISyntaxException, EaafStorageException { MockitoAnnotations.initMocks(this); registerSearchService = new RegisterSearchService(zmrClient, ernpClient); - task = new InitialSearchTask(new ArrayList<>(), registerSearchService); + task = new InitialSearchTask(new ArrayList<>(), registerSearchService, eidPostProcessor); MockHttpServletRequest httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); MockHttpServletResponse httpResp = new MockHttpServletResponse(); @@ -119,6 +128,24 @@ public class InitialSearchTaskTest { .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 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 */ @@ -245,7 +272,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new ItSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService); + registerSearchService, eidPostProcessor); task.execute(pendingReq1, executionContext); @@ -273,7 +300,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new DeSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService); + registerSearchService, eidPostProcessor); task.execute(pendingReq1, executionContext); @@ -307,7 +334,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new DeSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService); + registerSearchService, eidPostProcessor); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); @@ -340,7 +367,7 @@ public class InitialSearchTaskTest { Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); task = new InitialSearchTask( Collections.singletonList(new ItSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService); + registerSearchService, eidPostProcessor); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); -- cgit v1.2.3 From 9f0fa316c8f7adeb3529cb4c3b2c553f085f7d95 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Tue, 15 Jun 2021 12:14:51 +0200 Subject: add ZMR client, to some re-factoring, and a lot of bug-fixing --- .../modules/auth/eidas/v2/test/SzrClientTest.java | 2 +- .../eidas/v2/test/SzrClientTestProduction.java | 2 +- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 505 +++++++++++++-------- ...eceiveAustrianResidenceGuiResponseTaskTest.java | 142 ++++-- ...eceiveMobilePhoneSignatureResponseTaskTest.java | 158 ++++--- 5 files changed, 503 insertions(+), 306 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java index d861006e..2d493091 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java @@ -25,10 +25,10 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; 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.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.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; diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java index e50044c6..b9cc77b1 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java @@ -24,10 +24,10 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test; 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.asitplus.eidas.specific.modules.auth.eidas.v2.szr.SzrClient; 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; 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 index 643afb90..34bca782 100644 --- 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 @@ -23,20 +23,59 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +import java.math.BigInteger; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.xml.namespace.QName; + +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.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 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.ZmrRegisterResult; 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.EidPostProcessingException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasAttributeException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ManualFixNecessaryException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.DeSpecificDetailSearchProcessor; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasSAuthenticationException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.WorkflowException; +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.handler.ItSpecificDetailSearchProcessor; 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.tasks.InitialSearchTask; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.zmr.IZmrClient; +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; @@ -49,34 +88,6 @@ 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.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -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.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Map; -import java.util.Random; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertThrows; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { @@ -86,22 +97,32 @@ import static org.junit.Assert.assertThrows; @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class InitialSearchTaskTest { - private static final String DE_ST = "de/st/"; - private static final String IT_ST = "it/st/"; + + private static final String EE = "EE"; + private static final String DE = "DE"; + private static final String IT = "IT"; + + private static final String EE_ST = EE + "/ST/"; + private static final String DE_ST = DE + "/ST/"; + private static final String IT_ST = IT + "/ST/"; - private InitialSearchTask task; @Mock private IZmrClient zmrClient; @Mock private IErnpClient ernpClient; - private final ICcSpecificEidProcessingService eidPostProcessor = createEidPostProcessor(); + + @Autowired private List 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 randomIdentifier = RandomStringUtils.randomNumeric(10); - private final String randomPseudonym = DE_ST + randomIdentifier; + private final String randomPsydonym = RandomStringUtils.randomNumeric(10); + private final String randomPersonalIdentifier_DE = DE_ST + randomPsydonym; + private final String randomPersonalIdentifier_EE = EE_ST + randomPsydonym; private final String randomFamilyName = randomAlphabetic(10); private final String randomGivenName = randomAlphabetic(10); private final String randomPlaceOfBirth = randomAlphabetic(10); @@ -114,8 +135,9 @@ public class InitialSearchTaskTest { @Before public void setUp() throws URISyntaxException, EaafStorageException { MockitoAnnotations.initMocks(this); - registerSearchService = new RegisterSearchService(zmrClient, ernpClient); - task = new InitialSearchTask(new ArrayList<>(), registerSearchService, eidPostProcessor); + + registerSearchService = new RegisterSearchService(handlers, zmrClient, ernpClient); + task = new InitialSearchTask(registerSearchService, eidPostProcessor); MockHttpServletRequest httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); MockHttpServletResponse httpResp = new MockHttpServletResponse(); @@ -153,73 +175,119 @@ public class InitialSearchTaskTest { @DirtiesContext public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { String newFirstName = randomAlphabetic(10); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, newFirstName, randomFamilyName, randomBirthDate))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.singletonList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(newFirstName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()), + generateRandomProcessId())); task.execute(pendingReq, executionContext); String bPk = readBpkFromSessionData(pendingReq); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); + Assert.assertEquals("Wrong bpk", randomBpk, bPk); } /** * One match, but register update needed + * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException, EidasSAuthenticationException { + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); + String newRandomGivenName = randomAlphabetic(10); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate))); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.singletonList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(newRandomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build())); task.execute(pendingReq, executionContext); String bPk = readBpkFromSessionData(pendingReq); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); + Assert.assertEquals("Wrong bpk", randomBpk, bPk); } /** * Two matches found in ZMR + * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode101_ManualFixNecessary_a() { + public void testNode101_ManualFixNecessary_a() throws EidasSAuthenticationException { ArrayList zmrResult = new ArrayList<>(); - zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate)); + zmrResult.add( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()); String newRandomGivenName = randomGivenName + randomAlphabetic(2); - zmrResult.add(new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate)); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(zmrResult); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + zmrResult.add( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(newRandomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(zmrResult, generateRandomProcessId())); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong exception", (origE instanceof WorkflowException)); } /** * Two matches found in ErnP + * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode101_ManualFixNecessary_b() { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + public void testNode101_ManualFixNecessary_b() throws EidasSAuthenticationException { + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); ArrayList ernpResult = new ArrayList<>(); - ernpResult.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, randomFamilyName, randomBirthDate)); + ernpResult.add( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()); String newRandomGivenName = randomGivenName + randomAlphabetic(2); ernpResult.add( - new RegisterResult(randomBpk, randomIdentifier, newRandomGivenName, randomFamilyName, randomBirthDate)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(ernpResult); + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(newRandomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(ernpResult); TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong exception", (origE instanceof WorkflowException)); } /** @@ -228,13 +296,20 @@ public class InitialSearchTaskTest { @Test @DirtiesContext public void testNode102_UserIdentified_a() throws Exception { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.singletonList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build())); task.execute(pendingReq, executionContext); String bPk = readBpkFromSessionData(pendingReq); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); + Assert.assertEquals("Wrong bpk", randomBpk, bPk); } /** @@ -243,41 +318,22 @@ public class InitialSearchTaskTest { @Test @DirtiesContext public void testNode102_UserIdentified_b() throws Exception { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.singletonList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()), + generateRandomProcessId())); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); task.execute(pendingReq, executionContext); String bPk = readBpkFromSessionData(pendingReq); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); - } - - /** - * One match found in ZMR and ErnP with detail search - */ - @Test - @DirtiesContext - public void testNode103_UserIdentified_IT() throws Exception { - String taxNumber = RandomStringUtils.randomNumeric(14); - final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(taxNumber); - TestRequestImpl pendingReq1 = new TestRequestImpl(); - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - String newRandomIdentifier = randomIdentifier + RandomStringUtils.randomNumeric(2); - Mockito.when(zmrClient.searchItSpecific(taxNumber)).thenReturn(Collections.singletonList( - new RegisterResult(randomBpk, newRandomIdentifier, randomGivenName, randomFamilyName, - randomBirthDate, null, null, taxNumber, null))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new ItSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService, eidPostProcessor); - - task.execute(pendingReq1, executionContext); - - String bPk = readBpkFromSessionData(pendingReq1); - Assert.assertEquals("Wrong bpk", bPk, randomBpk); + Assert.assertEquals("Wrong bpk", randomBpk, bPk); } /** @@ -285,27 +341,38 @@ public class InitialSearchTaskTest { */ @Test @DirtiesContext - public void testNode103_UserIdentified_DE() throws Exception { + public void testNode103_UserIdentified_DE() throws Exception { final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, - randomPseudonym, + randomPersonalIdentifier_DE, randomBirthDate, randomPlaceOfBirth, randomBirthName); - TestRequestImpl pendingReq1 = new TestRequestImpl(); + TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomBirthDate, randomPlaceOfBirth, - randomBirthName)) - .thenReturn(Collections.singletonList(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, - randomFamilyName, randomBirthDate, randomPlaceOfBirth, randomBirthName, null, null))); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new DeSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService, eidPostProcessor); - + + BigInteger zmrProcessId = generateRandomProcessId(); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); + Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))).thenReturn( + new ZmrRegisterResult(Collections.singletonList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .placeOfBirth(randomPlaceOfBirth) + .birthName(randomBirthName) + .build()) + ,zmrProcessId)); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + + // execute test task.execute(pendingReq1, executionContext); + // validate state String resultBpk = readBpkFromSessionData(pendingReq1); - Assert.assertEquals("Wrong bpk", resultBpk, randomBpk); + Assert.assertEquals("Wrong bpk", randomBpk, resultBpk); + } /** @@ -314,76 +381,70 @@ public class InitialSearchTaskTest { @Test @DirtiesContext public void testNode104_ManualFixNecessary_DE() throws Exception { - String newRandomPseudonym = randomPseudonym + RandomStringUtils.randomNumeric(2); + String newRandomPseudonym = randomPersonalIdentifier_DE + RandomStringUtils.randomNumeric(2); String newRandomBpk = randomBpk + RandomStringUtils.randomNumeric(6); final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, - randomPseudonym, + randomPersonalIdentifier_DE, randomBirthDate, randomPlaceOfBirth, randomBirthName); TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - zmrResultSpecific.add( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate, - randomPlaceOfBirth, randomBirthName, null, null)); - zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, randomFamilyName, randomBirthDate, - randomPlaceOfBirth, randomBirthName, null, null)); - Mockito.when(zmrClient.searchDeSpecific(randomGivenName, randomFamilyName, randomBirthDate, randomPlaceOfBirth, - randomBirthName)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new DeSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService, eidPostProcessor); - + + BigInteger zmrProcessId = generateRandomProcessId(); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))).thenReturn( + new ZmrRegisterResult(Arrays.asList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .placeOfBirth(randomPlaceOfBirth) + .birthName(randomBirthName) + .build(), + RegisterResult.builder() + .bpk(newRandomBpk) + .pseudonym(Arrays.asList(newRandomPseudonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .placeOfBirth(randomPlaceOfBirth) + .birthName(randomBirthName) + .build()) + ,zmrProcessId)); + + + // execute test TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); + // check error Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); - } - - /** - * Multiple matches found in ZMR and ErnP with detail search - */ - @Test - @DirtiesContext - public void testNode104_ManualFixNecessary_IT() throws Exception { - String randomTaxNumber = RandomStringUtils.randomNumeric(14); - final AuthenticationResponse response = buildDummyAuthResponseRandomPersonIT_Tax(randomTaxNumber); - TestRequestImpl pendingReq1 = new TestRequestImpl(); - pendingReq1.getSessionData(AuthProcessDataWrapper.class) - .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList zmrResultSpecific = new ArrayList<>(); - String randomPseudonym = IT_ST + randomIdentifier + "4"; - zmrResultSpecific.add(new RegisterResult(randomBpk, randomPseudonym, randomGivenName, - randomFamilyName, randomBirthDate, null, null, randomTaxNumber, null)); - String newRandomPseudonym = IT_ST + randomIdentifier + "5"; - String newRandomBpk = RandomStringUtils.randomNumeric(6); - zmrResultSpecific.add(new RegisterResult(newRandomBpk, newRandomPseudonym, randomGivenName, - randomFamilyName, randomBirthDate, null, null, randomTaxNumber, null)); - Mockito.when(zmrClient.searchItSpecific(randomTaxNumber)).thenReturn(zmrResultSpecific); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - task = new InitialSearchTask( - Collections.singletonList(new ItSpecificDetailSearchProcessor(registerSearchService)), - registerSearchService, eidPostProcessor); - - TaskExecutionException exception = assertThrows(TaskExecutionException.class, - () -> task.execute(pendingReq1, executionContext)); - - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE instanceof ManualFixNecessaryException)); + Assert.assertTrue("Wrong exception", (origE instanceof WorkflowException)); } /** * NO match found in ZMR and ErnP with Initial and MDS search + * @throws EidasSAuthenticationException + * @throws URISyntaxException + * @throws EaafStorageException */ @Test @DirtiesContext - public void testNode505_TransitionToErnbTask() throws TaskExecutionException { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); + public void testNode505_TransitionToInsertErnbTask() 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, randomPersonalIdentifier_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()); task.execute(pendingReq, executionContext); @@ -398,21 +459,37 @@ public class InitialSearchTaskTest { /** * NO match found in ZMR and ErnP with Initial search, one match with MDS search in Ernb + * @throws EidasSAuthenticationException + * @throws URISyntaxException + * @throws EaafStorageException */ @Test @DirtiesContext - public void testNode505_TransitionToGUI_Ernb() throws TaskExecutionException { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - + public void testNode505_TransitionToGUI_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, randomPersonalIdentifier_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( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build())); task.execute(pendingReq, executionContext); - String bPk = readBpkFromSessionData(pendingReq); - Assert.assertNull("Wrong bpk", bPk); + assertThrows(WorkflowException.class, () -> readBpkFromSessionData(pendingReq)); 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); @@ -421,21 +498,29 @@ public class InitialSearchTaskTest { /** * NO match found in ZMR and ErnP with Initial search, one match with MDS search in ZMR + * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode505_TransitionToGUI_Zmr() throws TaskExecutionException { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - - Mockito.when(zmrClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn( - Collections.singletonList( - new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, randomBirthDate))); + public void testNode505_TransitionToGUI_Zmr() throws TaskExecutionException, EidasSAuthenticationException { + BigInteger zmrProcessId = generateRandomProcessId(); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + + Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, DE)).thenReturn( + new ZmrRegisterResult(Collections.singletonList(RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()), + zmrProcessId)); task.execute(pendingReq, executionContext); - String bPk = readBpkFromSessionData(pendingReq); - Assert.assertNull("Wrong bpk", bPk); + assertThrows(WorkflowException.class, () -> readBpkFromSessionData(pendingReq)); 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); @@ -444,23 +529,40 @@ public class InitialSearchTaskTest { /** * NO match found in ZMR and ErnP with Initial search, multiple matches found with MDS search + * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode505_TransitionToGUI_Ernb_multi() throws TaskExecutionException { - Mockito.when(zmrClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomIdentifier)).thenReturn(Collections.emptyList()); - ArrayList ernbResult = new ArrayList<>(); - ernbResult.add(new RegisterResult(randomBpk, randomIdentifier, randomGivenName, randomFamilyName, - randomBirthDate)); - ernbResult.add(new RegisterResult(randomBpk + "1", randomIdentifier, randomGivenName, randomFamilyName, - randomBirthDate)); - Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn(ernbResult); + public void testNode505_TransitionToGUI_Ernb_multi() throws TaskExecutionException, EidasSAuthenticationException { + BigInteger zmrProcessId = generateRandomProcessId(); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_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( + new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); + + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn( + Arrays.asList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build(), + RegisterResult.builder() + .bpk(randomBpk + "1") + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build())); task.execute(pendingReq, executionContext); - String bPk = readBpkFromSessionData(pendingReq); - Assert.assertNull("Wrong bpk", bPk); + assertThrows(WorkflowException.class, () -> readBpkFromSessionData(pendingReq)); 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); @@ -469,15 +571,14 @@ public class InitialSearchTaskTest { @NotNull private AuthenticationResponse buildDummyAuthResponseRandomPerson() throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomIdentifier, randomBirthDate); + return buildDummyAuthResponse(randomGivenName, randomFamilyName, DE_ST + randomPsydonym, randomBirthDate); } - private AuthenticationResponse buildDummyAuthResponseRandomPersonIT_Tax(String taxNumber) - throws URISyntaxException { - return buildDummyAuthResponse(randomGivenName, randomFamilyName, IT_ST + randomIdentifier, randomBirthDate, - taxNumber, null, null); + private BigInteger generateRandomProcessId() { + return new BigInteger(RandomStringUtils.randomNumeric(10)); + } - + @NotNull private AuthenticationResponse buildDummyAuthResponse(String givenName, String familyName, String identifier, String dateOfBirth) throws URISyntaxException { @@ -545,8 +646,10 @@ public class InitialSearchTaskTest { .attributeValueMarshaller(marshaller).build(); } - private String readBpkFromSessionData(TestRequestImpl pendingReq) { - return (String) pendingReq.getSessionData(AuthProcessDataWrapper.class) - .getGenericDataFromSession(Constants.DATA_RESULT_MATCHING_BPK); + private String readBpkFromSessionData(TestRequestImpl pendingReq) throws WorkflowException { + return MatchingTaskUtils.getInitialRegisterResult(pendingReq) != null + ? MatchingTaskUtils.getInitialRegisterResult(pendingReq).getBpk() + : null; + } } 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 index d9405251..281be36f 100644 --- 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 @@ -1,20 +1,20 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.dao.MergedRegisterSearchResult; -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.tasks.ReceiveAustrianResidenceGuiResponseTask; -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 com.google.common.collect.Lists; +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; @@ -32,14 +32,25 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import java.util.Collections; -import java.util.List; +import com.google.common.collect.Lists; -import static at.asitplus.eidas.specific.modules.auth.eidas.v2.tasks.ReceiveAustrianResidenceGuiResponseTask.*; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.springframework.util.Assert.isInstanceOf; +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.RegisterSearchResult; +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 = { @@ -50,11 +61,12 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { @Autowired protected MsConnectorDummyConfigMap authConfig; - @Autowired - private ReceiveAustrianResidenceGuiResponseTask task; + @MockBean private RegisterSearchService registerSearchService; + private ReceiveAustrianResidenceGuiResponseTask task; + private final ExecutionContext executionContext = new ExecutionContextImpl(); private MockHttpServletRequest httpReq; private MockHttpServletResponse httpResp; @@ -69,6 +81,8 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { 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(); @@ -85,9 +99,10 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { public void noRegisterResult() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - MergedRegisterSearchResult registerSearchResult = buildEmptyResult(); - mockRegisterSearch(userInput, registerSearchResult); - + RegisterSearchResult registerSearchResult = buildEmptyResult(); + mockRegisterSearch(userInput, registerSearchResult, eidasData); + MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + task.execute(pendingReq, executionContext); assertEquals("Transition To S9", true, executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); @@ -97,21 +112,24 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { public void exactlyOneRegisterResult_Matching() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - MergedRegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildMatchingRegisterResult(eidasData)); - mockRegisterSearch(userInput, registerSearchResult); + RegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildMatchingRegisterResult(eidasData)); + MatchingTaskUtils.storeInitialRegisterResult(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(any(), eq(registerSearchResult), eq(eidasData), eq(pendingReq)); + Mockito.verify(registerSearchService).step7aKittProcess(eq(registerSearchResult), eq(eidasData)); + } @Test public void exactlyOneRegisterResult_NotMatching() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - MergedRegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildNotMatchingRegisterResult(eidasData)); - mockRegisterSearch(userInput, registerSearchResult); + RegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildNotMatchingRegisterResult(eidasData)); + MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + mockRegisterSearch(userInput, registerSearchResult, eidasData); task.execute(pendingReq, executionContext); @@ -122,8 +140,9 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { public void moreThanOneRegisterResult() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - MergedRegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); - mockRegisterSearch(userInput, registerSearchResult); + RegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); + MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + mockRegisterSearch(userInput, registerSearchResult, eidasData); TaskExecutionException e = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); @@ -133,37 +152,70 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { assertNull("Transition To S16", executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); } - private void mockRegisterSearch(UserInput userInput, MergedRegisterSearchResult registerSearchResult) { - Mockito.when(registerSearchService.searchWithResidence(eq(userInput.getZipcode()), eq(userInput.getCity()), eq(userInput.getStreet()))).thenReturn(registerSearchResult); + private void mockRegisterSearch(UserInput userInput, RegisterSearchResult 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 MergedRegisterSearchResult buildEmptyResult() { - return new MergedRegisterSearchResult(Collections.emptyList(), Collections.emptyList()); + private RegisterSearchResult buildEmptyResult() { + return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + Collections.emptyList(), Collections.emptyList()); + } + private BigInteger generateRandomProcessId() { + return new BigInteger(RandomStringUtils.randomNumeric(10)); + + } + @NotNull - private MergedRegisterSearchResult buildResultWithOneMatch(RegisterResult registerResult) { - return new MergedRegisterSearchResult(Collections.singletonList(registerResult), Collections.emptyList()); + private RegisterSearchResult buildResultWithOneMatch(RegisterResult registerResult) { + return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + Collections.singletonList(registerResult), Collections.emptyList()); + } @NotNull - private MergedRegisterSearchResult buildResultWithTwoMatches() { + private RegisterSearchResult buildResultWithTwoMatches() { List results = Lists.newArrayList(buildRandomRegisterResult(), buildRandomRegisterResult()); - return new MergedRegisterSearchResult(results, Collections.emptyList()); + return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + results, Collections.emptyList()); + } @NotNull private RegisterResult buildRandomRegisterResult() { - return new RegisterResult(RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8), RandomStringUtils.randomAlphabetic(8)); + 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 new RegisterResult(RandomStringUtils.randomAlphabetic(8), eidData.getPseudonym(), eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth()); + 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 new RegisterResult(RandomStringUtils.randomAlphabetic(8), eidData.getPseudonym() + RandomStringUtils.randomAlphabetic(8), eidData.getGivenName(), eidData.getFamilyName(), eidData.getDateOfBirth()); + 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) { 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 index 77b87264..8c137bb2 100644 --- 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 @@ -1,8 +1,50 @@ 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.MergedRegisterSearchResult; 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; @@ -11,9 +53,12 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.IdAustri 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.RegisterSearchResult; 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; @@ -26,45 +71,7 @@ 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 com.google.common.collect.Lists; import net.shibboleth.utilities.java.support.xml.ParserPool; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.jetbrains.annotations.NotNull; -import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -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 javax.xml.transform.TransformerException; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.springframework.util.Assert.isInstanceOf; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { @@ -278,9 +285,8 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { task.execute(pendingReq, executionContext); - assertTrue("process not cancelled", executionContext.isProcessCancelled()); - assertTrue("process not stopped by user", pendingReq.isAbortedByUser()); - assertFalse("should not authenticated", pendingReq.isAuthenticated()); + assertEquals("Transition To S16", true, executionContext.get(Constants.TRANSITION_TO_GENERATE_GUI_QUERY_AUSTRIAN_RESIDENCE_TASK)); + } @Test @@ -327,6 +333,8 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { 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(); @@ -334,9 +342,10 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - MergedRegisterSearchResult registerSearchResult = new MergedRegisterSearchResult(Collections.emptyList(), Collections.emptyList()); - Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(registerSearchResult); - + RegisterSearchResult registerSearchResult = new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + Collections.emptyList(), Collections.emptyList()); + MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + task.execute(pendingReq, executionContext); AuthProcessDataWrapper session = pendingReq.getSessionData(AuthProcessDataWrapper.class); @@ -353,8 +362,8 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - MergedRegisterSearchResult registerSearchResult = buildResultWithOneMatch(); - Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(registerSearchResult); + RegisterSearchResult registerSearchResult = buildResultWithOneMatch(); + MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); task.execute(pendingReq, executionContext); @@ -363,9 +372,13 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { 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)); - Mockito.verify(registerSearchService).step7aKittProcess(any(), eq(registerSearchResult), eq(eidData), eq(pendingReq)); + + //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(); @@ -373,34 +386,63 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - MergedRegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); - Mockito.when(registerSearchService.searchWithBpkZp(eq(BPK_FROM_ID_AUSTRIA))).thenReturn(registerSearchResult); - 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); + + + 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 MergedRegisterSearchResult buildResultWithOneMatch() { - return new MergedRegisterSearchResult(Collections.singletonList(new RegisterResult(BPK_FROM_ID_AUSTRIA, "bar", "foo", "foo", "bar")), Collections.emptyList()); + private RegisterSearchResult buildResultWithOneMatch() { + return new RegisterSearchResult(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 MergedRegisterSearchResult buildResultWithTwoMatches() { - List results = Lists.newArrayList(new RegisterResult(BPK_FROM_ID_AUSTRIA, "bar", "foo", "foo", "bar"), - new RegisterResult("bpk", "pseudonym", "givenName", "familyName", "dateOfBirth")); - return new MergedRegisterSearchResult(results, Collections.emptyList()); + private RegisterSearchResult buildResultWithTwoMatches() { + List 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 RegisterSearchResult(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() -- cgit v1.2.3 From 6e1a69773284177a0f6c7233c4bcdf7f4bd96681 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Tue, 15 Jun 2021 18:15:19 +0200 Subject: further optimizations and bug fixing in matching code --- .../modules/auth/eidas/v2/test/dummy/DummyOA.java | 18 +- .../DeSpecificDetailSearchProcessorTest.java | 105 ++++++ .../ItSpecificDetailSearchProcessorTes.java | 84 +++++ .../tasks/CreateIdentityLinkTaskEidNewTest.java | 165 ++++++++- .../v2/test/tasks/CreateIdentityLinkTaskTest.java | 138 ++++++- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 409 ++++++++++++++------- ...eceiveAustrianResidenceGuiResponseTaskTest.java | 8 +- ...eceiveMobilePhoneSignatureResponseTaskTest.java | 4 +- 8 files changed, 771 insertions(+), 160 deletions(-) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/DeSpecificDetailSearchProcessorTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/handler/ItSpecificDetailSearchProcessorTes.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index 2f7782ae..074dd0bb 100644 --- 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 @@ -1,13 +1,19 @@ 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.idp.auth.builder.BpkBuilder; import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import lombok.Getter; import lombok.Setter; -import org.apache.commons.lang3.StringUtils; - -import java.util.*; public class DummyOA implements IAhSpConfiguration { @@ -115,13 +121,13 @@ public class DummyOA implements IAhSpConfiguration { } @Override - public List getTargetsWithNoBaseIdInternalProcessingRestriction() { + public Set getTargetsWithNoBaseIdInternalProcessingRestriction() { // TODO Auto-generated method stub return null; } @Override - public List getTargetsWithNoBaseIdTransferRestriction() { + public Set getTargetsWithNoBaseIdTransferRestriction() { // TODO Auto-generated method stub return null; } 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/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 248b71d9..7af9706e 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 @@ -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; @@ -39,16 +41,25 @@ import org.springframework.web.context.request.ServletRequestAttributes; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.skjolberg.mockito.soap.SoapServiceRule; 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; @@ -68,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; @@ -96,6 +109,9 @@ public class CreateIdentityLinkTaskEidNewTest { @Autowired EaafKeyStoreFactory keyStoreFactory; + @Autowired + ICcSpecificEidProcessingService eidPostProcessor; + @Autowired private IRequestStorage requestStorage; @@ -123,9 +139,11 @@ public class CreateIdentityLinkTaskEidNewTest { /** * 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(); @@ -144,8 +162,14 @@ public class CreateIdentityLinkTaskEidNewTest { response = buildDummyAuthResponse(false); pendingReq.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - - + + final Map 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/"); @@ -163,8 +187,10 @@ 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); val signContentResp = new SignContentResponseType(); @@ -223,7 +249,7 @@ public class CreateIdentityLinkTaskEidNewTest { verify(szrMock, times(1)).getStammzahlEncrypted(argument4.capture(), argument5.capture()); Boolean param5 = argument5.getValue(); - Assert.assertFalse("insertERnP flag", param5); + Assert.assertTrue("insertERnP flag", param5); PersonInfoType person = argument4.getValue(); Assert.assertEquals("FamilyName", response.getAttributes().getAttributeValuesByFriendlyName("FamilyName").getFirstValue( @@ -296,6 +322,82 @@ public class CreateIdentityLinkTaskEidNewTest { } + @Test + public void successfulProcessWithDataFromMatching() 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); + + 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.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 argument4 = ArgumentCaptor.forClass(PersonInfoType.class); + ArgumentCaptor 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 @@ -337,7 +439,7 @@ public class CreateIdentityLinkTaskEidNewTest { verify(szrMock, times(1)).getStammzahlEncrypted(argument4.capture(), argument5.capture()); Boolean param5 = argument5.getValue(); - Assert.assertFalse("insertERnP flag", param5); + Assert.assertTrue("insertERnP flag", param5); PersonInfoType person = argument4.getValue(); Assert.assertEquals("FamilyName", response.getAttributes().getAttributeValuesByFriendlyName("FamilyName").getFirstValue( @@ -456,4 +558,53 @@ public class CreateIdentityLinkTaskEidNewTest { .attributes(attributeMap.build()) .build(); } + + private Map convertEidasAttrToSimpleMap( + ImmutableMap, ImmutableSet>> attributeMap) { + final Map 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, + ImmutableSet>> attributeMap, + Map result, AttributeDefinition el) { + final List 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, + ImmutableSet>> attributeMap, + Map 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, + ImmutableSet>> attributeMap, + Map 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 556bd2eb..0a2d4271 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,7 +13,9 @@ 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; @@ -27,13 +30,22 @@ 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.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.skjolberg.mockito.soap.SoapServiceRule; 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; @@ -50,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; @@ -79,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; @@ -96,9 +113,11 @@ public class CreateIdentityLinkTaskTest { /** * 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(); @@ -117,9 +136,15 @@ public class CreateIdentityLinkTaskTest { pendingReq = new TestRequestImpl(); response = buildDummyAuthResponse(); - + final Map 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/"); @@ -181,6 +206,63 @@ public class CreateIdentityLinkTaskTest { } + @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 public void buildIdentityLinkWithWbpk() throws Exception { //initialize test @@ -444,4 +526,54 @@ public class CreateIdentityLinkTaskTest { .attributes(attributeMap) .build(); } + + private Map convertEidasAttrToSimpleMap( + ImmutableMap, ImmutableSet>> attributeMap) { + final Map 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, + ImmutableSet>> attributeMap, + Map result, AttributeDefinition el) { + final List 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, + ImmutableSet>> attributeMap, + Map 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, + ImmutableSet>> attributeMap, + Map 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/InitialSearchTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/InitialSearchTaskTest.java index 34bca782..bb732f1c 100644 --- 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 @@ -24,14 +24,18 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -44,6 +48,7 @@ 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; @@ -62,6 +67,7 @@ import org.springframework.web.context.request.ServletRequestAttributes; 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.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; @@ -69,10 +75,12 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidPostProcess import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasAttributeException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasSAuthenticationException; import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.WorkflowException; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ZmrCommunicationException; 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.RegisterSearchResult; 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; @@ -100,11 +108,9 @@ public class InitialSearchTaskTest { private static final String EE = "EE"; private static final String DE = "DE"; - private static final String IT = "IT"; private static final String EE_ST = EE + "/ST/"; private static final String DE_ST = DE + "/ST/"; - private static final String IT_ST = IT + "/ST/"; @Mock private IZmrClient zmrClient; @@ -173,130 +179,215 @@ public class InitialSearchTaskTest { */ @Test @DirtiesContext - public void testNode100_UserIdentifiedUpdateNecessary_a() throws Exception { - String newFirstName = randomAlphabetic(10); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + public void singlePersonalIdMatchUpdateNecessary_Zmr() throws Exception { + String oldGivenName = randomAlphabetic(10); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.singletonList( RegisterResult.builder() .bpk(randomBpk) .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(newFirstName) + .givenName(oldGivenName) .familyName(randomFamilyName) .dateOfBirth(randomBirthDate) .build()), generateRandomProcessId())); + + 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")); + + // execute test task.execute(pendingReq, executionContext); - String bPk = readBpkFromSessionData(pendingReq); - - Assert.assertEquals("Wrong bpk", randomBpk, bPk); + + // validate state + //INFO: has to be the old givenName because ZMR allows no update of MDS information + checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, oldGivenName, randomBirthDate, DE); + } + /** - * One match, but register update needed + * TODO: include again if ERnP update is implementet. Maybe we can update MDS based on ERnP. + * + * One match, but register update needed. * @throws EidasSAuthenticationException */ + @Ignore @Test @DirtiesContext - public void testNode100_UserIdentifiedUpdateNecessary_b() throws TaskExecutionException, EidasSAuthenticationException { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + public void singlePersonalIdMatchUpdateNecessary_Ernp() throws TaskExecutionException, EidasSAuthenticationException { + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); - String newRandomGivenName = randomAlphabetic(10); + String oldRandomGivenName = randomAlphabetic(10); Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.singletonList( RegisterResult.builder() .bpk(randomBpk) .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(newRandomGivenName) + .givenName(oldRandomGivenName) .familyName(randomFamilyName) .dateOfBirth(randomBirthDate) .build())); + // execute test task.execute(pendingReq, executionContext); - String bPk = readBpkFromSessionData(pendingReq); - - Assert.assertEquals("Wrong bpk", randomBpk, bPk); + + // validate state + checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); } /** - * Two matches found in ZMR + * Two matches by PersonalId found in ZMR * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode101_ManualFixNecessary_a() throws EidasSAuthenticationException { - ArrayList zmrResult = new ArrayList<>(); - zmrResult.add( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()); - String newRandomGivenName = randomGivenName + randomAlphabetic(2); - zmrResult.add( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(newRandomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( - new ZmrRegisterResult(zmrResult, generateRandomProcessId())); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + public void multiPersonalIdMatch_Zmr() throws EidasSAuthenticationException { + String newRandomGivenName = randomAlphabetic(10); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( + new ZmrRegisterResult(Arrays.asList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build(), + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(newRandomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build() + ), + generateRandomProcessId())); + Mockito.when(ernpClient.searchWithPersonIdentifier( + randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + // execute task TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq, executionContext)); - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE instanceof WorkflowException)); + + // validate state + assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); + assertTrue("Wrong flag 'manualFixNeeded'", + ((WorkflowException)exception.getOriginalException()).isRequiresManualFix()); + } - /** - * Two matches found in ErnP + * Two matches by PersonalId found in ZMR * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode101_ManualFixNecessary_b() throws EidasSAuthenticationException { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); - ArrayList ernpResult = new ArrayList<>(); - ernpResult.add( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()); - String newRandomGivenName = randomGivenName + randomAlphabetic(2); - ernpResult.add( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(newRandomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(ernpResult); + public void withErrorFromZmr() throws EidasSAuthenticationException { + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, 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)); - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE instanceof WorkflowException)); + + // validate state + assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); + assertFalse("Wrong flag 'manualFixNeeded'", + ((WorkflowException)exception.getOriginalException()).isRequiresManualFix()); + } /** - * One match, no register update needed + * Two matches by PersonalId found in ErnP + * @throws EidasSAuthenticationException */ @Test @DirtiesContext - public void testNode102_UserIdentified_a() throws Exception { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + public void multiPersonalIdMatch_Ernp() throws EidasSAuthenticationException { + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); + String newRandomGivenName = randomAlphabetic(10); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn( + Arrays.asList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build(), + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(newRandomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build() + )); + + // 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, randomPsydonym, DE)).thenReturn( + new ZmrRegisterResult(Arrays.asList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build() + ), generateRandomProcessId())); + String newRandomGivenName = randomAlphabetic(10); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn( + Arrays.asList( + RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build() + )); + + // 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, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.singletonList( RegisterResult.builder() @@ -307,18 +398,20 @@ public class InitialSearchTaskTest { .dateOfBirth(randomBirthDate) .build())); + // execute test task.execute(pendingReq, executionContext); - String bPk = readBpkFromSessionData(pendingReq); - Assert.assertEquals("Wrong bpk", randomBpk, bPk); + + // validate state + checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); } /** - * One match, no register update needed + * One match by PersonalId, no register update needed */ @Test @DirtiesContext - public void testNode102_UserIdentified_b() throws Exception { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + public void singlePersonalIdMatchNoUpdate_Zmr() throws Exception { + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.singletonList( RegisterResult.builder() .bpk(randomBpk) @@ -330,27 +423,27 @@ public class InitialSearchTaskTest { generateRandomProcessId())); Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + // execute test task.execute(pendingReq, executionContext); - - String bPk = readBpkFromSessionData(pendingReq); - Assert.assertEquals("Wrong bpk", randomBpk, bPk); + + // validate state + checkMatchingSuccessState(pendingReq, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); } /** - * Multiple matches found in ZMR and ErnP with detail search + * Find single person in ZMR by country specifics. */ @Test @DirtiesContext - public void testNode103_UserIdentified_DE() throws Exception { + public void singlePersonFindWithCountySpecifics_Zmr() throws Exception { final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, - randomPersonalIdentifier_DE, - randomBirthDate, randomPlaceOfBirth, randomBirthName); + 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, randomPersonalIdentifier_DE)).thenReturn( + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))).thenReturn( new ZmrRegisterResult(Collections.singletonList( @@ -364,23 +457,25 @@ public class InitialSearchTaskTest { .birthName(randomBirthName) .build()) ,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 - String resultBpk = readBpkFromSessionData(pendingReq1); - Assert.assertEquals("Wrong bpk", randomBpk, resultBpk); + checkMatchingSuccessState(pendingReq1, randomBpk, randomFamilyName, randomGivenName, randomBirthDate, DE); } /** - * Multiple matches found in ZMR and ErnP with detail search + * Multiple matches found in ZMR by country specifics. */ @Test @DirtiesContext - public void testNode104_ManualFixNecessary_DE() throws Exception { + 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, @@ -391,9 +486,8 @@ public class InitialSearchTaskTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); BigInteger zmrProcessId = generateRandomProcessId(); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( + new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))).thenReturn( new ZmrRegisterResult(Arrays.asList( RegisterResult.builder() @@ -416,14 +510,17 @@ public class InitialSearchTaskTest { .build()) ,zmrProcessId)); + Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); - // execute test + // execute task TaskExecutionException exception = assertThrows(TaskExecutionException.class, () -> task.execute(pendingReq1, executionContext)); - - // check error - Throwable origE = exception.getOriginalException(); - Assert.assertTrue("Wrong exception", (origE instanceof WorkflowException)); + + // validate state + assertTrue("Wrong exception", (exception.getOriginalException() instanceof WorkflowException)); + assertTrue("Wrong flag 'manualFixNeeded'", + ((WorkflowException)exception.getOriginalException()).isRequiresManualFix()); + } /** @@ -434,44 +531,51 @@ public class InitialSearchTaskTest { */ @Test @DirtiesContext - public void testNode505_TransitionToInsertErnbTask() throws TaskExecutionException, EidasSAuthenticationException, URISyntaxException, EaafStorageException { + 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, randomPersonalIdentifier_EE)).thenReturn( + + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, 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()); + + // execute task task.execute(pendingReq, executionContext); - String bPk = readBpkFromSessionData(pendingReq); - Assert.assertNull("Wrong bpk", bPk); + + // 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); + } /** - * NO match found in ZMR and ErnP with Initial search, one match with MDS search in Ernb - * @throws EidasSAuthenticationException - * @throws URISyntaxException - * @throws EaafStorageException + * Find one match with MDS search in ERnP. */ @Test @DirtiesContext - public void testNode505_TransitionToGUI_Ernb() throws TaskExecutionException, EidasSAuthenticationException, URISyntaxException, EaafStorageException { + 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, randomPersonalIdentifier_EE)).thenReturn( + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, EE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, EE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); @@ -487,24 +591,22 @@ public class InitialSearchTaskTest { .dateOfBirth(randomBirthDate) .build())); + // execute test task.execute(pendingReq, executionContext); - assertThrows(WorkflowException.class, () -> readBpkFromSessionData(pendingReq)); - 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); + // validate state + checkIntermediateResult(1); + } /** - * NO match found in ZMR and ErnP with Initial search, one match with MDS search in ZMR - * @throws EidasSAuthenticationException + * Find one match with MDS search in ZMR. */ @Test @DirtiesContext - public void testNode505_TransitionToGUI_Zmr() throws TaskExecutionException, EidasSAuthenticationException { + public void resultByMdsSearch_Zmr() throws TaskExecutionException, EidasSAuthenticationException { BigInteger zmrProcessId = generateRandomProcessId(); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); @@ -518,29 +620,35 @@ public class InitialSearchTaskTest { .build()), zmrProcessId)); + // execute test task.execute(pendingReq, executionContext); - assertThrows(WorkflowException.class, () -> readBpkFromSessionData(pendingReq)); - 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); + // validate state + checkIntermediateResult(1); + } /** - * NO match found in ZMR and ErnP with Initial search, multiple matches found with MDS search - * @throws EidasSAuthenticationException + * resultByMdsSearch */ @Test @DirtiesContext - public void testNode505_TransitionToGUI_Ernb_multi() throws TaskExecutionException, EidasSAuthenticationException { + public void multipleResultsByMdsSearch() throws TaskExecutionException, EidasSAuthenticationException { BigInteger zmrProcessId = generateRandomProcessId(); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPersonalIdentifier_DE)).thenReturn( + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, 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( - new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); + new ZmrRegisterResult(Arrays.asList( + RegisterResult.builder() + .bpk(randomBpk + "2") + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .build()), + zmrProcessId)); Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); Mockito.when(ernpClient.searchWithMds(randomGivenName, randomFamilyName, randomBirthDate)).thenReturn( @@ -560,13 +668,12 @@ public class InitialSearchTaskTest { .dateOfBirth(randomBirthDate) .build())); + // execute test task.execute(pendingReq, executionContext); - assertThrows(WorkflowException.class, () -> readBpkFromSessionData(pendingReq)); - 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); + // validate state + checkIntermediateResult(3); + } @NotNull @@ -579,6 +686,38 @@ public class InitialSearchTaskTest { } + 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)); + + RegisterSearchResult 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 { @@ -646,10 +785,4 @@ public class InitialSearchTaskTest { .attributeValueMarshaller(marshaller).build(); } - private String readBpkFromSessionData(TestRequestImpl pendingReq) throws WorkflowException { - return MatchingTaskUtils.getInitialRegisterResult(pendingReq) != null - ? MatchingTaskUtils.getInitialRegisterResult(pendingReq).getBpk() - : null; - - } } 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 index 281be36f..77c49bb4 100644 --- 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 @@ -101,7 +101,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { SimpleEidasData eidasData = setupEidasData(); RegisterSearchResult registerSearchResult = buildEmptyResult(); mockRegisterSearch(userInput, registerSearchResult, eidasData); - MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); task.execute(pendingReq, executionContext); @@ -113,7 +113,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); RegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildMatchingRegisterResult(eidasData)); - MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); mockRegisterSearch(userInput, registerSearchResult, eidasData); task.execute(pendingReq, executionContext); @@ -128,7 +128,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); RegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildNotMatchingRegisterResult(eidasData)); - MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); mockRegisterSearch(userInput, registerSearchResult, eidasData); task.execute(pendingReq, executionContext); @@ -141,7 +141,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); RegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); - MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); mockRegisterSearch(userInput, registerSearchResult, eidasData); TaskExecutionException e = assertThrows(TaskExecutionException.class, 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 index 8c137bb2..51077e96 100644 --- 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 @@ -344,7 +344,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); RegisterSearchResult registerSearchResult = new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), Collections.emptyList(), Collections.emptyList()); - MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); task.execute(pendingReq, executionContext); @@ -363,7 +363,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); RegisterSearchResult registerSearchResult = buildResultWithOneMatch(); - MatchingTaskUtils.storeInitialRegisterResult(pendingReq, registerSearchResult); + MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); task.execute(pendingReq, executionContext); -- cgit v1.2.3 From 249e3805da249afafe164ae7dc43884ba3777727 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Wed, 16 Jun 2021 11:51:11 +0200 Subject: add ZMR update process into ZMRClient --- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 47 ++++++++++++++++------ ...eceiveAustrianResidenceGuiResponseTaskTest.java | 24 +++++------ ...eceiveMobilePhoneSignatureResponseTaskTest.java | 14 +++---- 3 files changed, 54 insertions(+), 31 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index bb732f1c..cca94188 100644 --- 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 @@ -80,7 +80,7 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.handler.CountrySpecificD 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.RegisterSearchResult; +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; @@ -196,6 +196,8 @@ public class InitialSearchTaskTest { 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); @@ -422,7 +424,9 @@ public class InitialSearchTaskTest { .build()), generateRandomProcessId())); 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); @@ -443,20 +447,31 @@ public class InitialSearchTaskTest { .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); BigInteger zmrProcessId = generateRandomProcessId(); + RegisterResult zmrResult = RegisterResult.builder() + .bpk(randomBpk) + .pseudonym(Arrays.asList(randomPsydonym)) + .givenName(randomGivenName) + .familyName(randomFamilyName) + .dateOfBirth(randomBirthDate) + .placeOfBirth(randomPlaceOfBirth) + .birthName(randomBirthName) + .build(); Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))).thenReturn( - new ZmrRegisterResult(Collections.singletonList( - RegisterResult.builder() + new ZmrRegisterResult(Collections.singletonList(zmrResult) + ,zmrProcessId)); + Mockito.when(zmrClient.update(eq(zmrProcessId), eq(zmrResult) , any())).thenReturn( + new ZmrRegisterResult(Collections.singletonList(RegisterResult.builder() .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) + .pseudonym(Arrays.asList(randomPsydonym, RandomStringUtils.randomAlphanumeric(10))) .givenName(randomGivenName) .familyName(randomFamilyName) .dateOfBirth(randomBirthDate) .placeOfBirth(randomPlaceOfBirth) .birthName(randomBirthName) - .build()) - ,zmrProcessId)); + .build()) + ,zmrProcessId)); Mockito.when(zmrClient.searchWithMds(any(), any(), any(), any(), any())).thenThrow( new IllegalStateException("MDS search should not be neccessary")); @@ -541,9 +556,12 @@ public class InitialSearchTaskTest { 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); @@ -608,8 +626,6 @@ public class InitialSearchTaskTest { BigInteger zmrProcessId = generateRandomProcessId(); Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); - Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, DE)).thenReturn( new ZmrRegisterResult(Collections.singletonList(RegisterResult.builder() .bpk(randomBpk) @@ -619,7 +635,12 @@ public class InitialSearchTaskTest { .dateOfBirth(randomBirthDate) .build()), 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); @@ -649,7 +670,9 @@ public class InitialSearchTaskTest { .dateOfBirth(randomBirthDate) .build()), 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( @@ -712,7 +735,7 @@ public class InitialSearchTaskTest { assertNull("Find final matching data but no match sould be found", MatchingTaskUtils.getFinalMatchingResult(pendingReq)); - RegisterSearchResult result = MatchingTaskUtils.getIntermediateMatchingResult(pendingReq); + RegisterStatusResults result = MatchingTaskUtils.getIntermediateMatchingResult(pendingReq); assertNotNull("Find no intermediate matching data", result); assertEquals("wrong intermediate result size", resultSize, result.getResultCount()); 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 index 77c49bb4..25a77cce 100644 --- 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 @@ -41,7 +41,7 @@ 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.RegisterSearchResult; +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; @@ -99,7 +99,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { public void noRegisterResult() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - RegisterSearchResult registerSearchResult = buildEmptyResult(); + RegisterStatusResults registerSearchResult = buildEmptyResult(); mockRegisterSearch(userInput, registerSearchResult, eidasData); MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); @@ -112,7 +112,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { public void exactlyOneRegisterResult_Matching() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - RegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildMatchingRegisterResult(eidasData)); + RegisterStatusResults registerSearchResult = buildResultWithOneMatch(buildMatchingRegisterResult(eidasData)); MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); mockRegisterSearch(userInput, registerSearchResult, eidasData); @@ -127,7 +127,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { public void exactlyOneRegisterResult_NotMatching() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - RegisterSearchResult registerSearchResult = buildResultWithOneMatch(buildNotMatchingRegisterResult(eidasData)); + RegisterStatusResults registerSearchResult = buildResultWithOneMatch(buildNotMatchingRegisterResult(eidasData)); MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); mockRegisterSearch(userInput, registerSearchResult, eidasData); @@ -140,7 +140,7 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { public void moreThanOneRegisterResult() throws Exception { UserInput userInput = setupUserInput(); SimpleEidasData eidasData = setupEidasData(); - RegisterSearchResult registerSearchResult = buildResultWithTwoMatches(); + RegisterStatusResults registerSearchResult = buildResultWithTwoMatches(); MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); mockRegisterSearch(userInput, registerSearchResult, eidasData); @@ -152,14 +152,14 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { assertNull("Transition To S16", executionContext.get(Constants.TRANSITION_TO_CREATE_NEW_ERNP_ENTRY_TASK)); } - private void mockRegisterSearch(UserInput userInput, RegisterSearchResult registerSearchResult, SimpleEidasData eidasData ) { + 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 RegisterSearchResult buildEmptyResult() { - return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + private RegisterStatusResults buildEmptyResult() { + return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), Collections.emptyList(), Collections.emptyList()); } @@ -170,16 +170,16 @@ public class ReceiveAustrianResidenceGuiResponseTaskTest { } @NotNull - private RegisterSearchResult buildResultWithOneMatch(RegisterResult registerResult) { - return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + private RegisterStatusResults buildResultWithOneMatch(RegisterResult registerResult) { + return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), Collections.singletonList(registerResult), Collections.emptyList()); } @NotNull - private RegisterSearchResult buildResultWithTwoMatches() { + private RegisterStatusResults buildResultWithTwoMatches() { List results = Lists.newArrayList(buildRandomRegisterResult(), buildRandomRegisterResult()); - return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), results, Collections.emptyList()); } 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 index 51077e96..b072b8b2 100644 --- 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 @@ -54,7 +54,7 @@ import at.asitplus.eidas.specific.modules.auth.eidas.v2.idaustriaclient.provider 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.RegisterSearchResult; +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; @@ -342,7 +342,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - RegisterSearchResult registerSearchResult = new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + RegisterStatusResults registerSearchResult = new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), Collections.emptyList(), Collections.emptyList()); MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); @@ -362,7 +362,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); SimpleEidasData eidData = createEidasDataMatchingToSamlResponse().build(); authProcessData.setGenericDataToSession(Constants.DATA_SIMPLE_EIDAS, eidData); - RegisterSearchResult registerSearchResult = buildResultWithOneMatch(); + RegisterStatusResults registerSearchResult = buildResultWithOneMatch(); MatchingTaskUtils.storeIntermediateMatchingResult(pendingReq, registerSearchResult); task.execute(pendingReq, executionContext); @@ -403,8 +403,8 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { } @NotNull - private RegisterSearchResult buildResultWithOneMatch() { - return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + private RegisterStatusResults buildResultWithOneMatch() { + return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), Collections.singletonList(RegisterResult.builder() .bpk(BPK_FROM_ID_AUSTRIA) .pseudonym(Arrays.asList("bar")) @@ -417,7 +417,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { } @NotNull - private RegisterSearchResult buildResultWithTwoMatches() { + private RegisterStatusResults buildResultWithTwoMatches() { List results = Lists.newArrayList( RegisterResult.builder() .bpk(BPK_FROM_ID_AUSTRIA) @@ -434,7 +434,7 @@ public class ReceiveMobilePhoneSignatureResponseTaskTest { .dateOfBirth("dateOfBirth") .build()); - return new RegisterSearchResult(new RegisterOperationStatus(generateRandomProcessId()), + return new RegisterStatusResults(new RegisterOperationStatus(generateRandomProcessId()), results, Collections.emptyList()); } -- cgit v1.2.3 From cbf1d0408519d0763a1a87b733c16a1ba5d022ba Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Wed, 7 Jul 2021 09:31:43 +0200 Subject: add HTML template for additional eID information --- .../tasks/GenerateOtherLoginMethodGuiTaskTest.java | 143 +++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/GenerateOtherLoginMethodGuiTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 = + ""; + + @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("
")); + + return html; + + } +} -- cgit v1.2.3 From 39a7fdec4c4612e28c5ccc04a0b2d68328bbb946 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 12 Jul 2021 09:58:33 +0200 Subject: Rename test class to match implementation name --- .../test/tasks/ReceiveAuthnResponseTaskTest.java | 190 +++++++++++++++++++++ .../test/tasks/ReceiveEidasResponseTaskTest.java | 190 --------------------- 2 files changed, 190 insertions(+), 190 deletions(-) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAuthnResponseTaskTest.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveEidasResponseTaskTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAuthnResponseTaskTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAuthnResponseTaskTest.java new file mode 100644 index 00000000..c8e00e72 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveAuthnResponseTaskTest.java @@ -0,0 +1,190 @@ +package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; + +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; + +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.RandomStringUtils; +import org.jetbrains.annotations.NotNull; +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.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; +import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; +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.ReceiveAuthnResponseTask; +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; +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.EaafStorageException; +import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; +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 at.gv.egiz.eaaf.core.impl.utils.Random; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; +import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; +import lombok.val; + +@RunWith(SpringJUnit4ClassRunner.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml"}) +public class ReceiveAuthnResponseTaskTest { + + @Autowired(required = true) + private ReceiveAuthnResponseTask task; + + @Autowired(required = true) + 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. + */ + @Before + public void setUp() throws EaafStorageException, URISyntaxException { + + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false"); + + final Map spConfig = new HashMap<>(); + spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); + spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); + spConfig.put(PROP_CONFIG_SP_NEW_EID_MODE, "true"); + oaParam = new MsConnectorDummySpConfiguration(spConfig, basicConfig); + oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH)); + pendingReq = new TestRequestImpl(); + + 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, "LU"); + executionContext.put(EaafConstants.PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT, true); + + } + + @Test + public void missingEidasResponse() { + try { + task.execute(pendingReq, executionContext); + Assert.fail("No eIDAS response not detected"); + + } catch (TaskExecutionException e) { + Assert.assertEquals("ErrorId", "eidas.01", + ((EaafException) e.getOriginalException()).getErrorId()); + + } + } + + @Test + public void notSuccessEidasResponse() throws URISyntaxException { + String statusCode = RandomStringUtils.randomAlphabetic(10); + 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", + ((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 { + @NotNull + AuthenticationResponse eidasResponse = buildDummyAuthResponse(Constants.SUCCESS_URI); + httpReq.setAttribute(Constants.DATA_FULL_EIDAS_RESPONSE, eidasResponse); + 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 AuthProcessDataWrapper authProcessData = storedReq.getSessionData(AuthProcessDataWrapper.class); + Assert.assertEquals("LoA", eidasResponse.getLevelOfAssurance(), authProcessData.getQaaLevel()); + Assert.assertNotNull("eIDAS response", + authProcessData.getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE)); + Assert.assertEquals("eIDAS response", eidasResponse, + authProcessData.getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE)); + + } + + @NotNull + private AuthenticationResponse buildDummyAuthResponse(String statusCode) throws URISyntaxException { + final AttributeDefinition attributeDef = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( + Constants.eIDAS_ATTR_PERSONALIDENTIFIER).first(); + final AttributeDefinition attributeDef2 = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( + Constants.eIDAS_ATTR_CURRENTFAMILYNAME).first(); + final AttributeDefinition attributeDef3 = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( + 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)) + .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)).put(attributeDef4, "2001-01-01").build(); + + val b = new AuthenticationResponse.Builder(); + return b.id("_".concat(Random.nextHexRandom16())) + .issuer(RandomStringUtils.randomAlphabetic(10)) + .subject(RandomStringUtils.randomAlphabetic(10)) + .statusCode(statusCode) + .inResponseTo("_".concat(Random.nextHexRandom16())) + .subjectNameIdFormat("afaf") + .levelOfAssurance(EaafConstants.EIDAS_LOA_HIGH) + .attributes(attributeMap) + .build(); + } + +} 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/ReceiveEidasResponseTaskTest.java deleted file mode 100644 index ae3a79b8..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/tasks/ReceiveEidasResponseTaskTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; - -import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; - -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.RandomStringUtils; -import org.jetbrains.annotations.NotNull; -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.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import at.asitplus.eidas.specific.connector.MsEidasNodeConstants; -import at.asitplus.eidas.specific.connector.test.config.dummy.MsConnectorDummyConfigMap; -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.ReceiveAuthnResponseTask; -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; -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.EaafStorageException; -import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; -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 at.gv.egiz.eaaf.core.impl.utils.Random; -import eu.eidas.auth.commons.attribute.AttributeDefinition; -import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; -import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; -import lombok.val; - -@RunWith(SpringJUnit4ClassRunner.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) -@ContextConfiguration(locations = { - "/SpringTest-context_tasks_test.xml", - "/SpringTest-context_basic_mapConfig.xml"}) -public class ReceiveEidasResponseTaskTest { - - @Autowired(required = true) - private ReceiveAuthnResponseTask task; - - @Autowired(required = true) - 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. - */ - @Before - public void setUp() throws EaafStorageException, URISyntaxException { - - httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); - httpResp = new MockHttpServletResponse(); - RequestContextHolder.resetRequestAttributes(); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - - basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.debug.useDummySolution", "false"); - - final Map spConfig = new HashMap<>(); - spConfig.put(EaafConfigConstants.SERVICE_UNIQUEIDENTIFIER, "testSp"); - spConfig.put("target", "urn:publicid:gv.at:cdid+XX"); - spConfig.put(PROP_CONFIG_SP_NEW_EID_MODE, "true"); - oaParam = new MsConnectorDummySpConfiguration(spConfig, basicConfig); - oaParam.setLoa(Arrays.asList(EaafConstants.EIDAS_LOA_HIGH)); - pendingReq = new TestRequestImpl(); - - 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, "LU"); - executionContext.put(EaafConstants.PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT, true); - - } - - @Test - public void missingEidasResponse() { - try { - task.execute(pendingReq, executionContext); - Assert.fail("No eIDAS response not detected"); - - } catch (TaskExecutionException e) { - Assert.assertEquals("ErrorId", "eidas.01", - ((EaafException) e.getOriginalException()).getErrorId()); - - } - } - - @Test - public void notSuccessEidasResponse() throws URISyntaxException { - String statusCode = RandomStringUtils.randomAlphabetic(10); - 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", - ((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 { - @NotNull - AuthenticationResponse eidasResponse = buildDummyAuthResponse(Constants.SUCCESS_URI); - httpReq.setAttribute(Constants.DATA_FULL_EIDAS_RESPONSE, eidasResponse); - 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 AuthProcessDataWrapper authProcessData = storedReq.getSessionData(AuthProcessDataWrapper.class); - Assert.assertEquals("LoA", eidasResponse.getLevelOfAssurance(), authProcessData.getQaaLevel()); - Assert.assertNotNull("eIDAS response", - authProcessData.getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE)); - Assert.assertEquals("eIDAS response", eidasResponse, - authProcessData.getGenericDataFromSession(Constants.DATA_FULL_EIDAS_RESPONSE)); - - } - - @NotNull - private AuthenticationResponse buildDummyAuthResponse(String statusCode) throws URISyntaxException { - final AttributeDefinition attributeDef = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( - Constants.eIDAS_ATTR_PERSONALIDENTIFIER).first(); - final AttributeDefinition attributeDef2 = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( - Constants.eIDAS_ATTR_CURRENTFAMILYNAME).first(); - final AttributeDefinition attributeDef3 = attrRegistry.getCoreAttributeRegistry().getByFriendlyName( - 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)) - .put(attributeDef3, RandomStringUtils.randomAlphabetic(10)).put(attributeDef4, "2001-01-01").build(); - - val b = new AuthenticationResponse.Builder(); - return b.id("_".concat(Random.nextHexRandom16())) - .issuer(RandomStringUtils.randomAlphabetic(10)) - .subject(RandomStringUtils.randomAlphabetic(10)) - .statusCode(statusCode) - .inResponseTo("_".concat(Random.nextHexRandom16())) - .subjectNameIdFormat("afaf") - .levelOfAssurance(EaafConstants.EIDAS_LOA_HIGH) - .attributes(attributeMap) - .build(); - } - -} -- cgit v1.2.3 From f555785f594040b215c58fe0a83b8f9c0ca72024 Mon Sep 17 00:00:00 2001 From: Christian Kollmann Date: Mon, 12 Jul 2021 13:48:26 +0200 Subject: Refactor creating random results in tests --- .../eidas/v2/test/tasks/InitialSearchTaskTest.java | 666 +++++++++------------ 1 file changed, 293 insertions(+), 373 deletions(-) (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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 index cca94188..b0de3460 100644 --- 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 @@ -23,59 +23,15 @@ package at.asitplus.eidas.specific.modules.auth.eidas.v2.test.tasks; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; - -import java.math.BigInteger; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import javax.xml.namespace.QName; - -import org.apache.commons.lang3.RandomStringUtils; -import org.jetbrains.annotations.NotNull; -import org.junit.Assert; -import org.junit.Before; -import org.junit.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 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.EidPostProcessingException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasAttributeException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.EidasSAuthenticationException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.WorkflowException; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.exception.ZmrCommunicationException; +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; @@ -96,6 +52,36 @@ 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 = { @@ -105,10 +91,10 @@ import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; @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/"; @@ -116,19 +102,20 @@ public class InitialSearchTaskTest { private IZmrClient zmrClient; @Mock private IErnpClient ernpClient; - - @Autowired private List handlers; + + @Autowired + private List handlers; private RegisterSearchService registerSearchService; - - private final ICcSpecificEidProcessingService eidPostProcessor = createEidPostProcessor(); + + 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 randomPsydonym = RandomStringUtils.randomNumeric(10); - private final String randomPersonalIdentifier_DE = DE_ST + randomPsydonym; - private final String randomPersonalIdentifier_EE = EE_ST + randomPsydonym; + 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); @@ -141,7 +128,7 @@ public class InitialSearchTaskTest { @Before public void setUp() throws URISyntaxException, EaafStorageException { MockitoAnnotations.initMocks(this); - + registerSearchService = new RegisterSearchService(handlers, zmrClient, ernpClient); task = new InitialSearchTask(registerSearchService, eidPostProcessor); @@ -181,228 +168,170 @@ public class InitialSearchTaskTest { @DirtiesContext public void singlePersonalIdMatchUpdateNecessary_Zmr() throws Exception { String oldGivenName = randomAlphabetic(10); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.singletonList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(oldGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()), - generateRandomProcessId())); - - 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")); - + 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. - * + * TODO: include again if ERnP update is implementet. Maybe we can update MDS based on ERnP. + *

* One match, but register update needed. - * @throws EidasSAuthenticationException + * + * @throws EidasSAuthenticationException */ @Ignore @Test @DirtiesContext public void singlePersonalIdMatchUpdateNecessary_Ernp() throws TaskExecutionException, EidasSAuthenticationException { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); - + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) + .thenReturn(emptyZmrRegisterResult()); + String oldRandomGivenName = randomAlphabetic(10); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.singletonList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(oldRandomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build())); + 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 + * + * @throws EidasSAuthenticationException */ @Test @DirtiesContext public void multiPersonalIdMatch_Zmr() throws EidasSAuthenticationException { String newRandomGivenName = randomAlphabetic(10); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Arrays.asList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build(), - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(newRandomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build() - ), - generateRandomProcessId())); - Mockito.when(ernpClient.searchWithPersonIdentifier( - randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + 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()); - + assertTrue("Wrong flag 'manualFixNeeded'", + ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + } /** * Two matches by PersonalId found in ZMR - * @throws EidasSAuthenticationException + * + * @throws EidasSAuthenticationException */ @Test @DirtiesContext public void withErrorFromZmr() throws EidasSAuthenticationException { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenThrow( - new ZmrCommunicationException("jUnit ZMR error", null)); - Mockito.when(ernpClient.searchWithPersonIdentifier( - randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); + 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()); - + assertFalse("Wrong flag 'manualFixNeeded'", + ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + } /** * Two matches by PersonalId found in ErnP - * @throws EidasSAuthenticationException + * + * @throws EidasSAuthenticationException */ @Test @DirtiesContext public void multiPersonalIdMatch_Ernp() throws EidasSAuthenticationException { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) + .thenReturn(emptyZmrRegisterResult()); String newRandomGivenName = randomAlphabetic(10); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn( - Arrays.asList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build(), - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(newRandomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build() - )); + 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()); - + assertTrue("Wrong flag 'manualFixNeeded'", + ((WorkflowException) exception.getOriginalException()).isRequiresManualFix()); + } /** * Two matches by PersonalId - * @throws EidasSAuthenticationException + * + * @throws EidasSAuthenticationException */ @Test @DirtiesContext public void multiPersonalIdMatch_ErnpAndZmr() throws EidasSAuthenticationException { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Arrays.asList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build() - ), generateRandomProcessId())); + Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPseudonym, DE)) + .thenReturn(zmrRegisterResult(randomRegisterResult())); String newRandomGivenName = randomAlphabetic(10); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn( - Arrays.asList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build() - )); + 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()); - + 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, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), generateRandomProcessId())); - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.singletonList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build())); + 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); } @@ -413,23 +342,16 @@ public class InitialSearchTaskTest { @Test @DirtiesContext public void singlePersonalIdMatchNoUpdate_Zmr() throws Exception { - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.singletonList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()), - generateRandomProcessId())); - 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")); - + 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); } @@ -439,50 +361,50 @@ public class InitialSearchTaskTest { */ @Test @DirtiesContext - public void singlePersonFindWithCountySpecifics_Zmr() throws Exception { + public void singlePersonFindWithCountySpecifics_Zmr() throws Exception { final AuthenticationResponse response = buildDummyAuthResponseDE(randomGivenName, randomFamilyName, randomPersonalIdentifier_DE, randomBirthDate, randomPlaceOfBirth, randomBirthName); - TestRequestImpl pendingReq1 = new TestRequestImpl(); + TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - - BigInteger zmrProcessId = generateRandomProcessId(); + + BigInteger zmrProcessId = generateRandomProcessId(); RegisterResult zmrResult = RegisterResult.builder() .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) + .pseudonym(Collections.singletonList(randomPseudonym)) .givenName(randomGivenName) .familyName(randomFamilyName) .dateOfBirth(randomBirthDate) .placeOfBirth(randomPlaceOfBirth) .birthName(randomBirthName) - .build(); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); - Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))).thenReturn( - new ZmrRegisterResult(Collections.singletonList(zmrResult) - ,zmrProcessId)); - Mockito.when(zmrClient.update(eq(zmrProcessId), eq(zmrResult) , any())).thenReturn( - new ZmrRegisterResult(Collections.singletonList(RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym, RandomStringUtils.randomAlphanumeric(10))) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .placeOfBirth(randomPlaceOfBirth) - .birthName(randomBirthName) - .build()) - ,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()); + .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); - + } /** @@ -499,79 +421,80 @@ public class InitialSearchTaskTest { TestRequestImpl pendingReq1 = new TestRequestImpl(); pendingReq1.getSessionData(AuthProcessDataWrapper.class) .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, response); - - BigInteger zmrProcessId = generateRandomProcessId(); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); - Mockito.when(zmrClient.searchCountrySpecific(eq(zmrProcessId), any(PersonSuchenRequest.class), eq(DE))).thenReturn( - new ZmrRegisterResult(Arrays.asList( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .placeOfBirth(randomPlaceOfBirth) - .birthName(randomBirthName) - .build(), - RegisterResult.builder() - .bpk(newRandomBpk) - .pseudonym(Arrays.asList(newRandomPseudonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .placeOfBirth(randomPlaceOfBirth) - .birthName(randomBirthName) - .build()) - ,zmrProcessId)); - - Mockito.when(ernpClient.searchWithPersonIdentifier(randomPersonalIdentifier_DE)).thenReturn(Collections.emptyList()); - + + 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()); - + 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 + * + * @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, + .setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, buildDummyAuthResponse(randomGivenName, randomFamilyName, randomPersonalIdentifier_EE, randomBirthDate)); - - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, 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()); - - + + 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 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)); @@ -579,35 +502,29 @@ public class InitialSearchTaskTest { 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. + * 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, randomPsydonym, 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( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build())); + .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); @@ -618,35 +535,28 @@ public class InitialSearchTaskTest { } /** - * Find one match with MDS search in ZMR. + * 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, randomPsydonym, DE)).thenReturn( - new ZmrRegisterResult(Collections.emptyList(), zmrProcessId)); - Mockito.when(zmrClient.searchWithMds(zmrProcessId, randomGivenName, randomFamilyName, randomBirthDate, DE)).thenReturn( - new ZmrRegisterResult(Collections.singletonList(RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()), - zmrProcessId)); - Mockito.when(zmrClient.update(any(), any(), any())).thenThrow( - new IllegalStateException("ZMR update should not be neccessary")); - + 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); - + } /** @@ -655,66 +565,76 @@ public class InitialSearchTaskTest { @Test @DirtiesContext public void multipleResultsByMdsSearch() throws TaskExecutionException, EidasSAuthenticationException { - BigInteger zmrProcessId = generateRandomProcessId(); - Mockito.when(zmrClient.searchWithPersonIdentifier(null, randomPsydonym, 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( - new ZmrRegisterResult(Arrays.asList( - RegisterResult.builder() - .bpk(randomBpk + "2") - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build()), - 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( - RegisterResult.builder() - .bpk(randomBpk) - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build(), - RegisterResult.builder() - .bpk(randomBpk + "1") - .pseudonym(Arrays.asList(randomPsydonym)) - .givenName(randomGivenName) - .familyName(randomFamilyName) - .dateOfBirth(randomBirthDate) - .build())); + 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 + randomPsydonym, randomBirthDate); + 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)); + + 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()); @@ -722,25 +642,25 @@ public class InitialSearchTaskTest { assertEquals("wrong familyName", familyName, personInfo.getFamilyName()); assertEquals("wrong dateOfBirth", birhday, personInfo.getDateOfBirth()); assertEquals("wrong countryCode", countryCode, personInfo.getCountryCode()); - + } - - private void checkIntermediateResult(int resultSize) { + + 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)); + + 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 { -- cgit v1.2.3 From 256781d66e555a308b44c12438f45a1a6af28182 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Mon, 9 Aug 2021 15:06:05 +0200 Subject: move SZR-client tests into new package --- .../modules/auth/eidas/v2/test/SzrClientTest.java | 354 --------------------- .../eidas/v2/test/SzrClientTestProduction.java | 173 ---------- .../v2/test/clients/SzrClientProductionTest.java | 173 ++++++++++ .../auth/eidas/v2/test/clients/SzrClientTest.java | 354 +++++++++++++++++++++ 4 files changed, 527 insertions(+), 527 deletions(-) delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientProductionTest.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java deleted file mode 100644 index 2d493091..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTest.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright 2018 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; - -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.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.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.exceptions.EaafParserException; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; -import at.gv.egiz.eaaf.core.impl.utils.DomUtils; -import com.skjolberg.mockito.soap.SoapServiceRule; -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.junit.*; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -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 org.xml.sax.SAXException; -import szrservices.*; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.ws.soap.SOAPFaultException; -import java.io.IOException; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.Mockito.when; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "/SpringTest-context_tasks_test.xml", - "/SpringTest-context_basic_mapConfig.xml"}) -public class SzrClientTest { - private static final Logger log = LoggerFactory.getLogger(SzrClientTest.class); - - @Autowired SzrClient szrClient; - @Autowired MsConnectorDummyConfigMap basicConfig; - - private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; - - private SZR szrMock = null; - - @Rule - public SoapServiceRule soap = SoapServiceRule.newInstance(); - - /** - * Initialize jUnit test. - */ - @Before - public void initializer() { - if (szrMock == null) { - szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); - } - - basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.eidasbind.mds.inject", "false"); - } - - - @Test - public void getStammzahlenEcryptedTest() throws SZRException_Exception, SzrCommunicationException { - final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); - final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); - szrResponse.getOut().add(result1); - - result1.setKey(RandomStringUtils.randomAlphanumeric(20)); - - // when(szrMock.getBPKFromStammzahlEncrypted(anyList())) - // .thenReturn(Arrays.asList(result1)); - when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(result1.getKey()); - - String stammzahlEncrypted = szrClient.getEncryptedStammzahl(getEidData()); - - Assert.assertEquals("bcBind not match", result1.getKey(), stammzahlEncrypted); - - when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(null); - try { - szrClient.getEncryptedStammzahl(getEidData()); - } catch (SzrCommunicationException e) { - Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); - } - } - - @Test - public void getEidasBindRealSzrResponse() throws SZRException_Exception, SzrCommunicationException, IOException { - final SignContentResponse szrResponse = new SignContentResponse(); - final SignContentEntry result1 = new SignContentEntry(); - final SignContentResponseType content = new SignContentResponseType(); - content.getOut().add(result1); - szrResponse.setSignContentResponse(content); - - result1.setKey("bcBindReq"); - result1.setValue(IOUtils.toString(SzrClient.class.getResourceAsStream("/data/szr/signed_eidasBind.jws"))); - - when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); - - final String bcBind = szrClient - .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 { - szrClient - .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 - .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(); - content1.getOut().add(result2); - result2.setKey("bcBindReq"); - result2.setValue(""); - when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content1); - - try { - szrClient - .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 { - final SignContentResponse szrResponse = new SignContentResponse(); - final SignContentEntry result1 = new SignContentEntry(); - final SignContentResponseType content = new SignContentResponseType(); - content.getOut().add(result1); - szrResponse.setSignContentResponse(content); - - result1.setKey("bcBindReq"); - result1.setValue(RandomStringUtils.randomAlphanumeric(100)); - - when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); - - final String bcBind = szrClient - .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 { - 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(); - content.getOut().add(result1); - szrResponse.setSignContentResponse(content); - - result1.setKey("bcBindReq"); - result1.setValue(RandomStringUtils.randomAlphanumeric(100)); - - when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); - - final String bcBind = szrClient - .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, JAXBException { - setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml"); - - try { - log.debug("Starting connecting SZR Gateway"); - final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(getEidData()); - - Assert.assertNotNull(result); - Assert.assertNotNull(result.getAssertion()); - - final IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser((Element) result.getAssertion()) - .parseIdentityLink(); - Assert.assertNotNull(identityLink); - - System.out.println(identityLink.getSerializedSamlAssertion()); - - checkElement("Mustermann", identityLink.getFamilyName()); - checkElement("Hans", identityLink.getGivenName()); - checkElement("1989-05-05", identityLink.getDateOfBirth()); - checkElement("urn:publicid:gv.at:baseid", identityLink.getIdentificationType()); - checkElement("k+zDM1BVpN1WJO4x7ZQ3ng==", identityLink.getIdentificationValue()); - Assert.assertNotNull(identityLink.getSerializedSamlAssertion()); - Assert.assertNotNull(identityLink.getSamlAssertion()); - - } catch (final SzrCommunicationException e) { - Assert.fail(); - - } - - } - - @Test - public void getIdentityLinkRawModeErrorTravelerDocExists() - throws SZRException_Exception, IOException, ParserConfigurationException, SAXException { - setSzrExceptionIdentityLink("/data/szr/szr_resp_error_travelerdocexists.xml"); - - try { - log.debug("Starting connecting SZR Gateway"); - szrClient.getIdentityLinkInRawMode(getEidData()); - Assert.fail(); - - } catch (final SzrCommunicationException e) { - checkElement("ernb.02", e.getErrorId()); - Assert.assertNotNull(e.getCause()); - org.springframework.util.Assert.isInstanceOf(SOAPFaultException.class, e.getCause()); - Assert.assertNotNull(((SOAPFaultException) e.getCause()).getFault()); - checkElement("p344:F455", ((SOAPFaultException) e.getCause()).getFault().getFaultCode()); - checkElement( - "The travel document you sent to insert a person already exists for another person. " + "Either check the document or have the person altered accordingly", - ((SOAPFaultException) e.getCause()).getFault().getFaultString()); - - } - - } - - @Ignore - @Test - public void getBpkTest() throws EidasSAuthenticationException { - final List bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, basicConfig - .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")); - - if (bPK.isEmpty()) { - throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); - } - for (final String b : bPK) { - if (StringUtils.isEmpty(b)) { - throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); - } - } - - } - - private void checkElement(String expected, String value) { - Assert.assertNotNull(value); - Assert.assertEquals(expected, value); - - } - - @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, - org.w3._2000._09.xmldsig.ObjectFactory.class, - at.gv.e_government.reference.namespace.persondata._20020228.ObjectFactory.class); - final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - final GetIdentityLinkEidasResponse szrResponse = (GetIdentityLinkEidasResponse) jaxbUnmarshaller - .unmarshal(this.getClass().getResourceAsStream(responseXmlPath)); - when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenReturn(szrResponse.getGetIdentityLinkReturn()); - - } - - @SuppressWarnings("SameParameterValue") - private void setSzrExceptionIdentityLink(String responseXmlPath) - 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( - "The travel document you sent to insert a person already exists for another person. " + "Either check the document or have the person altered accordingly", - qName); - fault.setRole("urn:SZRServices"); - fault.setDetail(detailerror); - when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenThrow(fault); - - } - - private SimpleEidasData getEidData() { - return SimpleEidasData.builder() - .familyName("Mustermann") - .givenName("Franz") - .dateOfBirth("1989-05-05") - .citizenCountryCode("IS") - .pseudonym("1234sdgsdfg56789ABCDEF") - .build(); - } - - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java deleted file mode 100644 index b9cc77b1..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/SzrClientTestProduction.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2018 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; - -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.junit.Assert; -import org.junit.Ignore; -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.IfProfileValue; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.w3c.dom.Element; -import szrservices.IdentityLinkType; - -import java.util.List; - - -@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 SzrClientTestProduction { - private static final Logger log = LoggerFactory.getLogger(SzrClientTestProduction.class); - - @Autowired - SzrClient szrClient; - @Autowired - IConfiguration basicConfig; - - private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; - - @Test - public void dummyTest() { - - } - - @Test - public void getVsz() throws EidasSAuthenticationException { - String vsz = szrClient.getEncryptedStammzahl(getEidData()); - Assert.assertNotNull("vsz", vsz); - - } - - @Test - 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"; - - String eidasBind = szrClient.getEidasBind(vsz, bindingPubKey, eidStatus, getEidData()); - - Assert.assertNotNull("eidasBind", eidasBind); - - } - - - @Test - public void getIdentityLinkRawMode() throws EaafParserException, EidasSAuthenticationException { - log.debug("Starting connecting SZR Gateway"); - final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(getEidData()); - - final Element idlFromSzr = (Element) result.getAssertion(); - final IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser(idlFromSzr).parseIdentityLink(); - - if (identityLink == null) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO IDL object" }); - } - - System.out.println(identityLink.getSerializedSamlAssertion()); - - if (StringUtils.isEmpty(identityLink.getFamilyName())) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO FamilyName from IDL" }); - } - - if (StringUtils.isEmpty(identityLink.getGivenName())) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO GivenName from IDL" }); - } - - if (StringUtils.isEmpty(identityLink.getDateOfBirth())) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO DateOfBirthName from IDL" }); - } - - if (StringUtils.isEmpty(identityLink.getIdentificationType())) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO baseIdType from IDL" }); - } - - if (StringUtils.isEmpty(identityLink.getIdentificationValue())) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO baseId from IDL" }); - } - - if (StringUtils.isEmpty(identityLink.getSerializedSamlAssertion())) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO serialized IDL" }); - } - - if (identityLink.getSamlAssertion() == null) { - throw new SzrCommunicationException("ernb.00", new Object[] { "NO raw IDL" }); - } - - } - - - @Ignore - @Test - public void getBpkTest() throws EidasSAuthenticationException { - String vkz = basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined"); - final List bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, vkz); - - if (bPK.isEmpty()) { - throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); - } - for (String b : bPK) { - if (StringUtils.isEmpty(b)) { - throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); - } - } - - } - - private SimpleEidasData getEidData() { - return SimpleEidasData.builder() - .familyName("Mustermann") - .givenName("Franz") - .dateOfBirth("1989-05-04") - .citizenCountryCode("IS") - .pseudonym("1234ffgsdfg56789ABCDEF") - .build(); - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientProductionTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientProductionTest.java new file mode 100644 index 00000000..a5b83b13 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientProductionTest.java @@ -0,0 +1,173 @@ +/* + * Copyright 2018 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.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.junit.Assert; +import org.junit.Ignore; +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.IfProfileValue; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.w3c.dom.Element; +import szrservices.IdentityLinkType; + +import java.util.List; + + +@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 SzrClientProductionTest { + private static final Logger log = LoggerFactory.getLogger(SzrClientProductionTest.class); + + @Autowired + SzrClient szrClient; + @Autowired + IConfiguration basicConfig; + + private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; + + @Test + public void dummyTest() { + + } + + @Test + public void getVsz() throws EidasSAuthenticationException { + String vsz = szrClient.getEncryptedStammzahl(getEidData()); + Assert.assertNotNull("vsz", vsz); + + } + + @Test + 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"; + + String eidasBind = szrClient.getEidasBind(vsz, bindingPubKey, eidStatus, getEidData()); + + Assert.assertNotNull("eidasBind", eidasBind); + + } + + + @Test + public void getIdentityLinkRawMode() throws EaafParserException, EidasSAuthenticationException { + log.debug("Starting connecting SZR Gateway"); + final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(getEidData()); + + final Element idlFromSzr = (Element) result.getAssertion(); + final IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser(idlFromSzr).parseIdentityLink(); + + if (identityLink == null) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO IDL object" }); + } + + System.out.println(identityLink.getSerializedSamlAssertion()); + + if (StringUtils.isEmpty(identityLink.getFamilyName())) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO FamilyName from IDL" }); + } + + if (StringUtils.isEmpty(identityLink.getGivenName())) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO GivenName from IDL" }); + } + + if (StringUtils.isEmpty(identityLink.getDateOfBirth())) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO DateOfBirthName from IDL" }); + } + + if (StringUtils.isEmpty(identityLink.getIdentificationType())) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO baseIdType from IDL" }); + } + + if (StringUtils.isEmpty(identityLink.getIdentificationValue())) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO baseId from IDL" }); + } + + if (StringUtils.isEmpty(identityLink.getSerializedSamlAssertion())) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO serialized IDL" }); + } + + if (identityLink.getSamlAssertion() == null) { + throw new SzrCommunicationException("ernb.00", new Object[] { "NO raw IDL" }); + } + + } + + + @Ignore + @Test + public void getBpkTest() throws EidasSAuthenticationException { + String vkz = basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined"); + final List bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, vkz); + + if (bPK.isEmpty()) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); + } + for (String b : bPK) { + if (StringUtils.isEmpty(b)) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); + } + } + + } + + private SimpleEidasData getEidData() { + return SimpleEidasData.builder() + .familyName("Mustermann") + .givenName("Franz") + .dateOfBirth("1989-05-04") + .citizenCountryCode("IS") + .pseudonym("1234ffgsdfg56789ABCDEF") + .build(); + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientTest.java new file mode 100644 index 00000000..647e5d27 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/SzrClientTest.java @@ -0,0 +1,354 @@ +/* + * Copyright 2018 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.clients; + +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.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.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.exceptions.EaafParserException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import com.skjolberg.mockito.soap.SoapServiceRule; +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.junit.*; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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 org.xml.sax.SAXException; +import szrservices.*; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.ws.soap.SOAPFaultException; +import java.io.IOException; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.when; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "/SpringTest-context_tasks_test.xml", + "/SpringTest-context_basic_mapConfig.xml"}) +public class SzrClientTest { + private static final Logger log = LoggerFactory.getLogger(SzrClientTest.class); + + @Autowired SzrClient szrClient; + @Autowired MsConnectorDummyConfigMap basicConfig; + + private static final String DUMMY_TARGET = EaafConstants.URN_PREFIX_CDID + "ZP"; + + private SZR szrMock = null; + + @Rule + public SoapServiceRule soap = SoapServiceRule.newInstance(); + + /** + * Initialize jUnit test. + */ + @Before + public void initializer() { + if (szrMock == null) { + szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); + } + + basicConfig.putConfigValue("eidas.ms.auth.eIDAS.szrclient.eidasbind.mds.inject", "false"); + } + + + @Test + public void getStammzahlenEcryptedTest() throws SZRException_Exception, SzrCommunicationException { + final GetBPKFromStammzahlEncryptedResponse szrResponse = new GetBPKFromStammzahlEncryptedResponse(); + final GetBPKFromStammzahlEncryptedResponseType result1 = new GetBPKFromStammzahlEncryptedResponseType(); + szrResponse.getOut().add(result1); + + result1.setKey(RandomStringUtils.randomAlphanumeric(20)); + + // when(szrMock.getBPKFromStammzahlEncrypted(anyList())) + // .thenReturn(Arrays.asList(result1)); + when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(result1.getKey()); + + String stammzahlEncrypted = szrClient.getEncryptedStammzahl(getEidData()); + + Assert.assertEquals("bcBind not match", result1.getKey(), stammzahlEncrypted); + + when(szrMock.getStammzahlEncrypted(any(), any())).thenReturn(null); + try { + szrClient.getEncryptedStammzahl(getEidData()); + } catch (SzrCommunicationException e) { + Assert.assertTrue("Not correct error", e.getMessage().contains("ernb.01")); + } + } + + @Test + public void getEidasBindRealSzrResponse() throws SZRException_Exception, SzrCommunicationException, IOException { + final SignContentResponse szrResponse = new SignContentResponse(); + final SignContentEntry result1 = new SignContentEntry(); + final SignContentResponseType content = new SignContentResponseType(); + content.getOut().add(result1); + szrResponse.setSignContentResponse(content); + + result1.setKey("bcBindReq"); + result1.setValue(IOUtils.toString(SzrClient.class.getResourceAsStream("/data/szr/signed_eidasBind.jws"))); + + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); + + final String bcBind = szrClient + .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 { + szrClient + .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 + .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(); + content1.getOut().add(result2); + result2.setKey("bcBindReq"); + result2.setValue(""); + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content1); + + try { + szrClient + .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 { + final SignContentResponse szrResponse = new SignContentResponse(); + final SignContentEntry result1 = new SignContentEntry(); + final SignContentResponseType content = new SignContentResponseType(); + content.getOut().add(result1); + szrResponse.setSignContentResponse(content); + + result1.setKey("bcBindReq"); + result1.setValue(RandomStringUtils.randomAlphanumeric(100)); + + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); + + final String bcBind = szrClient + .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 { + 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(); + content.getOut().add(result1); + szrResponse.setSignContentResponse(content); + + result1.setKey("bcBindReq"); + result1.setValue(RandomStringUtils.randomAlphanumeric(100)); + + when(szrMock.signContent(any(), anyList(), anyList())).thenReturn(content); + + final String bcBind = szrClient + .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, JAXBException { + setSzrResponseIdentityLink("/data/szr/szr_resp_valid_1.xml"); + + try { + log.debug("Starting connecting SZR Gateway"); + final IdentityLinkType result = szrClient.getIdentityLinkInRawMode(getEidData()); + + Assert.assertNotNull(result); + Assert.assertNotNull(result.getAssertion()); + + final IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser((Element) result.getAssertion()) + .parseIdentityLink(); + Assert.assertNotNull(identityLink); + + System.out.println(identityLink.getSerializedSamlAssertion()); + + checkElement("Mustermann", identityLink.getFamilyName()); + checkElement("Hans", identityLink.getGivenName()); + checkElement("1989-05-05", identityLink.getDateOfBirth()); + checkElement("urn:publicid:gv.at:baseid", identityLink.getIdentificationType()); + checkElement("k+zDM1BVpN1WJO4x7ZQ3ng==", identityLink.getIdentificationValue()); + Assert.assertNotNull(identityLink.getSerializedSamlAssertion()); + Assert.assertNotNull(identityLink.getSamlAssertion()); + + } catch (final SzrCommunicationException e) { + Assert.fail(); + + } + + } + + @Test + public void getIdentityLinkRawModeErrorTravelerDocExists() + throws SZRException_Exception, IOException, ParserConfigurationException, SAXException { + setSzrExceptionIdentityLink("/data/szr/szr_resp_error_travelerdocexists.xml"); + + try { + log.debug("Starting connecting SZR Gateway"); + szrClient.getIdentityLinkInRawMode(getEidData()); + Assert.fail(); + + } catch (final SzrCommunicationException e) { + checkElement("ernb.02", e.getErrorId()); + Assert.assertNotNull(e.getCause()); + org.springframework.util.Assert.isInstanceOf(SOAPFaultException.class, e.getCause()); + Assert.assertNotNull(((SOAPFaultException) e.getCause()).getFault()); + checkElement("p344:F455", ((SOAPFaultException) e.getCause()).getFault().getFaultCode()); + checkElement( + "The travel document you sent to insert a person already exists for another person. " + "Either check the document or have the person altered accordingly", + ((SOAPFaultException) e.getCause()).getFault().getFaultString()); + + } + + } + + @Ignore + @Test + public void getBpkTest() throws EidasSAuthenticationException { + final List bPK = szrClient.getBpk(getEidData(), DUMMY_TARGET, basicConfig + .getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, "no VKZ defined")); + + if (bPK.isEmpty()) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK list is empty"}); + } + for (final String b : bPK) { + if (StringUtils.isEmpty(b)) { + throw new SzrCommunicationException("ernb.01", new Object[]{"bPK is null or empty"}); + } + } + + } + + private void checkElement(String expected, String value) { + Assert.assertNotNull(value); + Assert.assertEquals(expected, value); + + } + + @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, + org.w3._2000._09.xmldsig.ObjectFactory.class, + at.gv.e_government.reference.namespace.persondata._20020228.ObjectFactory.class); + final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + final GetIdentityLinkEidasResponse szrResponse = (GetIdentityLinkEidasResponse) jaxbUnmarshaller + .unmarshal(this.getClass().getResourceAsStream(responseXmlPath)); + when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenReturn(szrResponse.getGetIdentityLinkReturn()); + + } + + @SuppressWarnings("SameParameterValue") + private void setSzrExceptionIdentityLink(String responseXmlPath) + 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( + "The travel document you sent to insert a person already exists for another person. " + "Either check the document or have the person altered accordingly", + qName); + fault.setRole("urn:SZRServices"); + fault.setDetail(detailerror); + when(szrMock.getIdentityLinkEidas(any(PersonInfoType.class))).thenThrow(fault); + + } + + private SimpleEidasData getEidData() { + return SimpleEidasData.builder() + .familyName("Mustermann") + .givenName("Franz") + .dateOfBirth("1989-05-05") + .citizenCountryCode("IS") + .pseudonym("1234sdgsdfg56789ABCDEF") + .build(); + } + + +} -- cgit v1.2.3 From 847e690da4a2f6b08ca604538f1f42e6e6717d0b Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Mon, 9 Aug 2021 16:50:51 +0200 Subject: add ZMR-client test for development only that can be activated by Spring-Profile and uses real ZMR T-Stage (key material for authentication has to be available on local machine) --- .../v2/test/clients/ZmrClientProductionTest.java | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/eidas/specific/modules/auth/eidas/v2/test/clients/ZmrClientProductionTest.java (limited to 'eidas_modules/authmodule-eIDAS-v2/src/test/java') 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); + + } + +} -- cgit v1.2.3