diff options
Diffstat (limited to 'connector/src/test/java')
16 files changed, 1858 insertions, 119 deletions
diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java deleted file mode 100644 index 1721fe61..00000000 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthenticationDataBuilderTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package at.asitplus.eidas.specific.connector.test; - - -import at.asitplus.eidas.specific.connector.builder.AuthenticationDataBuilder; -import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; -import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; -import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; -import net.shibboleth.utilities.java.support.component.ComponentInitializationException; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opensaml.core.config.InitializationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import java.util.HashMap; -import java.util.Map; - -import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({"/applicationContext.xml", "/SpringTest_connector.beans.xml", "/eaaf_core.beans.xml", "/eaaf_pvp.beans.xml", "/eaaf_pvp_idp.beans.xml", "/spring/SpringTest-context_simple_storage.xml"}) -@WebAppConfiguration -public class AuthenticationDataBuilderTest { - - @Autowired - private AuthenticationDataBuilder authenticationDataBuilder; - - @Autowired(required = true) - private IConfiguration basicConfig; - - private MockHttpServletRequest httpReq; - private MockHttpServletResponse httpResp; - private TestRequestImpl pendingReq; - - private DummySpConfiguration oaParam; - - private String eidasBind; - private String authBlock; - - - @BeforeClass - public static void classInitializer() throws InitializationException, ComponentInitializationException { - final String current = new java.io.File(".").toURI().toString(); - System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_3.properties"); - - EaafOpenSaml3xInitializer.eaafInitialize(); - } - - @Before - public void initialize() throws EaafStorageException { - httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); - httpResp = new MockHttpServletResponse(); - RequestContextHolder.resetRequestAttributes(); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); - - final Map<String, String> 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 DummySpConfiguration(spConfig, basicConfig); - - pendingReq = new TestRequestImpl(); - pendingReq.setAuthUrl("https://localhost/ms_connector"); - pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); - pendingReq.setSpConfig(oaParam); - pendingReq.getSessionData(AuthProcessDataWrapper.class).setEidProcess(true); - authBlock = RandomStringUtils.randomAlphanumeric(20); - eidasBind = RandomStringUtils.randomAlphanumeric(20); - pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.SZR_AUTHBLOCK, authBlock); - pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession(Constants.EIDAS_BIND, eidasBind); - LocaleContextHolder.resetLocaleContext(); - } - - @Test - public void first() throws EaafAuthenticationException { - IAuthData authData = authenticationDataBuilder.buildAuthenticationData(pendingReq); - - Assert.assertNotNull("AuthData null", authData); - Assert.assertNotNull("authBlock null", authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class)); - Assert.assertNotNull("eidasBind null", authData.getGenericData(Constants.EIDAS_BIND, String.class)); - Assert.assertNotNull("eidasBind null", authData.getEidasQaaLevel()); - String authBlock = authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class); - String eidasBind = authData.getGenericData(Constants.EIDAS_BIND, String.class); - - Assert.assertEquals("authBlock not equal", authBlock, this.authBlock); - Assert.assertEquals("eidasBind not equal", eidasBind, this.eidasBind); - } - -} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/FullStartUpAndProcessTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/FullStartUpAndProcessTest.java new file mode 100644 index 00000000..77037415 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/FullStartUpAndProcessTest.java @@ -0,0 +1,485 @@ +package at.asitplus.eidas.specific.connector.test; + +import static org.mockito.ArgumentMatchers.any; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URISyntaxException; +import java.util.Map; +import java.util.Timer; + +import javax.xml.transform.TransformerException; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.ignite.Ignition; +import org.joda.time.DateTime; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.config.InitializationException; +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.metadata.resolver.impl.ResourceBackedMetadataResolver; +import org.opensaml.saml.saml2.core.RequestAbstractType; +import org.opensaml.saml.saml2.core.StatusResponseType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.core.io.ResourceLoader; +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.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.util.Base64Utils; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.skjolberg.mockito.soap.SoapServiceRule; + +import at.asitplus.eidas.specific.connector.controller.ProcessEngineSignalController; +import at.asitplus.eidas.specific.connector.controller.Pvp2SProfileEndpoint; +import at.asitplus.eidas.specific.connector.provider.PvpEndPointCredentialProvider; +import at.asitplus.eidas.specific.connector.provider.PvpMetadataProvider; +import at.asitplus.eidas.specific.connector.test.saml2.Pvp2SProfileEndPointTest; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.EidasSignalServlet; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.service.EidasAttributeRegistry; +import at.gv.egiz.components.spring.api.SpringBootApplicationContextInitializer; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.idp.controller.ProtocolFinalizationController; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import at.gv.egiz.eaaf.core.impl.utils.Random; +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.OpenSaml3ResourceAdapter; +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.impl.utils.AssertionAttributeExtractor; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; +import eu.eidas.auth.commons.light.ILightRequest; +import eu.eidas.auth.commons.protocol.impl.AuthenticationResponse; +import eu.eidas.auth.commons.tx.BinaryLightToken; +import eu.eidas.specificcommunication.SpecificCommunicationDefinitionBeanNames; +import eu.eidas.specificcommunication.exception.SpecificCommunicationException; +import eu.eidas.specificcommunication.protocol.SpecificCommunicationService; +import lombok.val; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; +import net.shibboleth.utilities.java.support.xml.XMLParserException; +import szrservices.SZR; +import szrservices.SignContentEntry; +import szrservices.SignContentResponseType; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest +@ContextConfiguration(initializers = { + org.springframework.boot.context.config.DelegatingApplicationContextInitializer.class, + SpringBootApplicationContextInitializer.class + }) +@TestPropertySource(locations = { "file:src/test/resources/config/junit_config_1_springboot.properties" }) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +@ActiveProfiles(profiles = {"JUNIT", "jUnitTestMode"}) +public class FullStartUpAndProcessTest { + + private static final String FINAL_REDIRECT = "http://localhost/finalizeAuthProtocol?pendingid="; + + @Autowired private WebApplicationContext wac; + @Autowired private PvpEndPointCredentialProvider credentialProvider; + @Autowired private PvpMetadataProvider metadataProvider; + @Autowired private ResourceLoader resourceLoader; + @Autowired private EidasAttributeRegistry attrRegistry; + + @Autowired private Pvp2SProfileEndpoint sProfile; + @Autowired private ProcessEngineSignalController signal; + @Autowired private EidasSignalServlet eidasSignal; + @Autowired private ProtocolFinalizationController finalize; + + @Rule + public final SoapServiceRule soap = SoapServiceRule.newInstance(); + + private SZR szrMock; + + private String cc; + private String givenName; + private String familyName; + private String dateOfBirth; + private String personalId; + private String vsz; + private String eidasBind; + + + /** + * jUnit class initializer. + * @throws InterruptedException In case of an error + * @throws ComponentInitializationException In case of an error + * @throws InitializationException In case of an error + * + */ + @BeforeClass + public static void classInitializer() throws InterruptedException, InitializationException, ComponentInitializationException { + final String current = new java.io.File(".").toURI().toString(); + System.clearProperty("eidas.ms.configuration"); + + //eIDAS Ref. Impl. properties + System.setProperty("EIDAS_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + System.setProperty("SPECIFIC_CONNECTOR_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + System.setProperty("SPECIFIC_PROXY_SERVICE_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + + EaafOpenSaml3xInitializer.eaafInitialize(); + + } + + /** + * Test shut-down. + * + * @throws IOException In case of an error + */ + @AfterClass + public static void closeIgniteNode() throws IOException { + System.out.println("Closiong Ignite Node ... "); + Ignition.stopAll(true); + + } + + /** + * jUnit test set-up. + * + * + */ + @Before + public void setup() throws IOException { + DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac); + @SuppressWarnings("rawtypes") + Map<String, FilterRegistrationBean> filters = wac.getBeansOfType(FilterRegistrationBean.class); + for (FilterRegistrationBean<?> filter : filters.values()) { + if (filter.isEnabled()) { + builder.addFilter(filter.getFilter(), "/*"); + + } + } + + szrMock = soap.mock(SZR.class, "http://localhost:1234/demoszr"); + + + + cc = RandomStringUtils.randomAlphabetic(2).toUpperCase(); + personalId = cc + "/AT/" + RandomStringUtils.randomNumeric(64); + familyName = RandomStringUtils.randomAlphabetic(10); + givenName = RandomStringUtils.randomAlphabetic(10); + dateOfBirth = "2015-10-12"; + + vsz = RandomStringUtils.randomNumeric(10); + eidasBind = RandomStringUtils.randomAlphanumeric(50); + + } + + @Test + public void userStopProcess() throws UnsupportedEncodingException, XMLParserException, UnmarshallingException, + TransformerException, IOException, MarshallingException, ComponentInitializationException, EaafException { + //start authentication process by sending a SAML2 Authn-Request + MockHttpServletRequest saml2Req = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + injectSaml2AuthnReq(saml2Req); + MockHttpServletResponse selectCountryResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(saml2Req, selectCountryResp)); + + // send SAML2 AuthnRequest + sProfile.pvpIdpPostRequest(saml2Req, selectCountryResp); + + //check country-selection response + Assert.assertEquals("no country-selection page", 200, selectCountryResp.getStatus()); + Assert.assertEquals("cc-selection page", "text/html;charset=UTF-8", selectCountryResp.getContentType()); + String selectionPage = selectCountryResp.getContentAsString(); + Assert.assertNotNull("selectionPage is null", selectionPage); + Assert.assertFalse("selectionPage is empty", selectionPage.isEmpty()); + + String pendingReqId = extractRequestToken(selectionPage, + "<input type=\"hidden\" name=\"pendingid\" value=\""); + Assert.assertFalse("PendingReqId", pendingReqId.isEmpty()); + + + // set-up user-stop request + MockHttpServletRequest userStopReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + userStopReq.setParameter("pendingid", pendingReqId); + userStopReq.setParameter(EaafConstants.PARAM_HTTP_STOP_PROCESS, "true"); + + MockHttpServletResponse finalizeResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(userStopReq, finalizeResp)); + + // send user-stop request + signal.performGenericAuthenticationProcess(userStopReq, finalizeResp); + + //validate state + Assert.assertEquals("forward to finalization", 302, finalizeResp.getStatus()); + Assert.assertNotNull("missing redirect header", finalizeResp.getHeader("Location")); + Assert.assertTrue("wrong redirect header", finalizeResp.getHeader("Location").startsWith(FINAL_REDIRECT)); + String finalPendingReqId = finalizeResp.getHeader("Location").substring(FINAL_REDIRECT.length()); + Assert.assertFalse("final pendingRequestId", finalPendingReqId.isEmpty()); + + //set-up finalization request + MockHttpServletRequest finalizationReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + finalizationReq.setParameter("pendingid", finalPendingReqId); + + MockHttpServletResponse saml2Resp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(finalizationReq, saml2Resp)); + + // exexcute finalization step + finalize.finalizeAuthProtocol(finalizationReq, saml2Resp); + + //validate state + Assert.assertEquals("forward to finalization", 200, saml2Resp.getStatus()); + Assert.assertEquals("forward to eIDAS Node page", "text/html;charset=UTF-8", saml2Resp.getContentType()); + String saml2RespPage = saml2Resp.getContentAsString(); + Assert.assertNotNull("selectionPage is null", saml2RespPage); + Assert.assertFalse("selectionPage is empty", saml2RespPage.isEmpty()); + + //validate SAML2 response + String saml2RespB64 = extractRequestToken(saml2RespPage, + "<input type=\"hidden\" name=\"SAMLResponse\" value=\""); + Assert.assertNotNull("SAML2 response", saml2RespB64); + + StatusResponseType saml2 = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + new ByteArrayInputStream(Base64Utils.decodeFromString(saml2RespB64))); + Assert.assertEquals("SAML2 status", "urn:oasis:names:tc:SAML:2.0:status:Responder", + saml2.getStatus().getStatusCode().getValue()); + Assert.assertEquals("ms-connector status", "1005", + saml2.getStatus().getStatusCode().getStatusCode().getValue()); + + } + + @Test + public void fullSuccessProcess() throws EaafException, Exception { + //start authentication process by sending a SAML2 Authn-Request + MockHttpServletRequest saml2Req = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + injectSaml2AuthnReq(saml2Req); + MockHttpServletResponse selectCountryResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(saml2Req, selectCountryResp)); + + // send SAML2 AuthnRequest + sProfile.pvpIdpPostRequest(saml2Req, selectCountryResp); + + //check country-selection response + Assert.assertEquals("no country-selection page", 200, selectCountryResp.getStatus()); + Assert.assertEquals("cc-selection page", "text/html;charset=UTF-8", selectCountryResp.getContentType()); + String selectionPage = selectCountryResp.getContentAsString(); + Assert.assertNotNull("selectionPage is null", selectionPage); + Assert.assertFalse("selectionPage is empty", selectionPage.isEmpty()); + + String pendingReqId = extractRequestToken(selectionPage, + "<input type=\"hidden\" name=\"pendingid\" value=\""); + Assert.assertFalse("PendingReqId", pendingReqId.isEmpty()); + + + // set-up country-selection request + MockHttpServletRequest selectCountryReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + selectCountryReq.setParameter("pendingid", pendingReqId); + selectCountryReq.setParameter("selectedCountry", cc); + + MockHttpServletResponse forwardEidasNodeResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(selectCountryReq, forwardEidasNodeResp)); + + // send country-selection request + signal.performGenericAuthenticationProcess(selectCountryReq, forwardEidasNodeResp); + + //check forward to eIDAS node response + Assert.assertEquals("forward to eIDAS Node", 200, forwardEidasNodeResp.getStatus()); + Assert.assertEquals("forward to eIDAS Node page", "text/html;charset=UTF-8", forwardEidasNodeResp.getContentType()); + String forwardPage = forwardEidasNodeResp.getContentAsString(); + Assert.assertNotNull("forward to eIDAS Node is null", forwardPage); + Assert.assertFalse("forward to eIDAS Node is empty", forwardPage.isEmpty()); + + String eidasNodeReqToken = extractRequestToken(forwardPage, + "<input type=\"hidden\" name=\"token\" value=\""); + Assert.assertFalse("eidas req. token", eidasNodeReqToken.isEmpty()); + + //check eIDAS node request and build respose + String eidasRespToken = validateEidasNodeRequestAndBuildResponse(eidasNodeReqToken); + Assert.assertFalse("eidas resp. token", eidasRespToken.isEmpty()); + + + // set-up eIDAS-node response + MockHttpServletRequest eidasNodeRespReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + eidasNodeRespReq.setParameter("token", eidasRespToken); + + MockHttpServletResponse finalizeResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(eidasNodeRespReq, finalizeResp)); + + injectSzrResponse(); + + //excute eIDAS node response + eidasSignal.restoreEidasAuthProcess(eidasNodeRespReq, finalizeResp); + + //validate state + Assert.assertEquals("forward to finalization", 302, finalizeResp.getStatus()); + Assert.assertNotNull("missing redirect header", finalizeResp.getHeader("Location")); + Assert.assertTrue("wrong redirect header", finalizeResp.getHeader("Location").startsWith(FINAL_REDIRECT)); + String finalPendingReqId = finalizeResp.getHeader("Location").substring(FINAL_REDIRECT.length()); + Assert.assertFalse("final pendingRequestId", finalPendingReqId.isEmpty()); + + + //set-up finalization request + MockHttpServletRequest finalizationReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + finalizationReq.setParameter("pendingid", finalPendingReqId); + + MockHttpServletResponse saml2Resp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(finalizationReq, saml2Resp)); + + // exexcute finalization step + finalize.finalizeAuthProtocol(finalizationReq, saml2Resp); + + //validate state + Assert.assertEquals("forward to finalization", 200, saml2Resp.getStatus()); + Assert.assertEquals("forward to eIDAS Node page", "text/html;charset=UTF-8", saml2Resp.getContentType()); + String saml2RespPage = saml2Resp.getContentAsString(); + Assert.assertNotNull("selectionPage is null", saml2RespPage); + Assert.assertFalse("selectionPage is empty", saml2RespPage.isEmpty()); + + //validate SAML2 response + String saml2RespB64 = extractRequestToken(saml2RespPage, + "<input type=\"hidden\" name=\"SAMLResponse\" value=\""); + Assert.assertNotNull("SAML2 response", saml2RespB64); + + StatusResponseType saml2 = (StatusResponseType) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + new ByteArrayInputStream(Base64Utils.decodeFromString(saml2RespB64))); + Assert.assertEquals("SAML2 status", Constants.SUCCESS_URI, saml2.getStatus().getStatusCode().getValue()); + + final AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(saml2); + Assert.assertEquals("wrong resp attr. size", 6, extractor.getAllIncludeAttributeNames().size()); + Assert.assertEquals("Wrong attr: LoA ", "http://eidas.europa.eu/LoA/high", + extractor.getSingleAttributeValue("urn:oid:1.2.40.0.10.2.1.1.261.108")); + Assert.assertEquals("Wrong attr: PVP_VERSION ", "2.2", + extractor.getSingleAttributeValue("urn:oid:1.2.40.0.10.2.1.1.261.10")); + Assert.assertEquals("Wrong attr: EID_ISSUER_NATION ", cc, + extractor.getSingleAttributeValue("urn:oid:1.2.40.0.10.2.1.1.261.32")); + Assert.assertEquals("Wrong attr: eidasBind", eidasBind, + extractor.getSingleAttributeValue("urn:eidgvat:attributes.eidbind")); + Assert.assertNotNull("Wrong attr: authBlock", + extractor.getSingleAttributeValue("urn:eidgvat:attributes.authblock.signed")); + Assert.assertNotNull("Wrong attr: piiTras.Id ", + extractor.getSingleAttributeValue("urn:eidgvat:attributes.piiTransactionId")); + + } + + private void injectSzrResponse() throws Exception { + + when(szrMock, "getStammzahlEncrypted", any(), any()).thenReturn(vsz); + val signContentResp = new SignContentResponseType(); + final SignContentEntry signContentEntry = new SignContentEntry(); + signContentEntry.setValue(eidasBind); + signContentResp.getOut().add(signContentEntry); + when(szrMock, "signContent", any(), any(), any()).thenReturn(signContentResp); + + } + + private String validateEidasNodeRequestAndBuildResponse(String eidasNodeReqToken) + throws SpecificCommunicationException, URISyntaxException { + final SpecificCommunicationService springManagedSpecificConnectorCommunicationService = + (SpecificCommunicationService) wac.getBean( + SpecificCommunicationDefinitionBeanNames.SPECIFIC_CONNECTOR_COMMUNICATION_SERVICE.toString()); + + //read request and validate basic properties + ILightRequest req = springManagedSpecificConnectorCommunicationService.getAndRemoveRequest(eidasNodeReqToken, + attrRegistry.getCoreAttributeRegistry().getAttributes()); + + Assert.assertNotNull("eIDAS Node req", req); + Assert.assertEquals("Wrong CC", cc, req.getCitizenCountryCode()); + Assert.assertEquals("Wrong CC", EaafConstants.EIDAS_LOA_HIGH, req.getLevelOfAssurance()); + + + //set response from eIDAS node + BinaryLightToken respoToken = springManagedSpecificConnectorCommunicationService.putResponse( + buildDummyAuthResponse(Constants.SUCCESS_URI, req.getId())); + return Base64Utils.encodeToString(respoToken.getTokenBytes()); + + } + + private AuthenticationResponse buildDummyAuthResponse(String statusCode, String reqId) 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, personalId) + .put(attributeDef2, familyName) + .put(attributeDef3, givenName) + .put(attributeDef4, dateOfBirth).build(); + + val b = new AuthenticationResponse.Builder(); + return b.id("_".concat(Random.nextHexRandom16())) + .issuer(RandomStringUtils.randomAlphabetic(10)) + .subject(RandomStringUtils.randomAlphabetic(10)) + .statusCode(statusCode) + .inResponseTo(reqId) + .subjectNameIdFormat("afaf") + .levelOfAssurance(EaafConstants.EIDAS_LOA_HIGH) + .attributes(attributeMap) + .build(); + + } + + private String extractRequestToken(String selectionPage, String selector) { + int start = selectionPage.indexOf(selector); + Assert.assertTrue("find no pendingReqId location start", start > 0); + int end = selectionPage.indexOf("\"", start + selector.length()); + Assert.assertTrue("find no pendingReqId location end", end > 0); + return selectionPage.substring(start + selector.length(), end); + + } + + private void injectSaml2AuthnReq(MockHttpServletRequest saml2Req) throws XMLParserException, UnmarshallingException, + SamlSigningException, CredentialsNotAvailableException, UnsupportedEncodingException, TransformerException, + IOException, MarshallingException, ComponentInitializationException { + final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + Pvp2SProfileEndPointTest.class.getResourceAsStream("/data/pvp2_authn_1.xml")); + authnReq.setIssueInstant(DateTime.now()); + RequestAbstractType signedAuthnReq = + Saml2Utils.signSamlObject(authnReq, credentialProvider.getMessageSigningCredential(), true); + String b64 = Base64Utils.encodeToString(DomUtils.serializeNode( + XMLObjectSupport.getMarshaller(signedAuthnReq).marshall(signedAuthnReq)).getBytes("UTF-8")); + saml2Req.setParameter("SAMLRequest", b64); + + final org.springframework.core.io.Resource resource = resourceLoader.getResource( + "classpath:/data/metadata_valid_without_encryption.xml"); + Timer timer = new Timer("PVP metadata-resolver refresh"); + ResourceBackedMetadataResolver fileSystemResolver = + new ResourceBackedMetadataResolver(timer, new OpenSaml3ResourceAdapter(resource)); + fileSystemResolver.setId("test"); + fileSystemResolver.setParserPool(XMLObjectProviderRegistrySupport.getParserPool()); + fileSystemResolver.initialize(); + metadataProvider.addMetadataResolverIntoChain(fileSystemResolver); + + } +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/MainClassExecutableModeTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/MainClassExecutableModeTest.java new file mode 100644 index 00000000..86df55df --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/MainClassExecutableModeTest.java @@ -0,0 +1,113 @@ +package at.asitplus.eidas.specific.connector.test; + +import java.io.IOException; +import java.lang.reflect.Field; + +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.ignite.Ignition; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.BlockJUnit4ClassRunner; + +import at.asitplus.eidas.specific.connector.SpringBootApplicationInitializer; +import at.gv.egiz.eaaf.core.impl.logging.DummyStatusMessager; +import at.gv.egiz.eaaf.core.impl.logging.LogMessageProviderFactory; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RunWith(BlockJUnit4ClassRunner.class) +public class MainClassExecutableModeTest { + + /** + * jUnit class initializer. + * @throws InterruptedException In case of an error + * + */ + @BeforeClass + public static void classInitializer() throws InterruptedException { + final String current = new java.io.File(".").toURI().toString(); + System.clearProperty("eidas.ms.configuration"); + + //eIDAS Ref. Impl. properties + System.setProperty("EIDAS_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + System.setProperty("SPECIFIC_CONNECTOR_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + System.setProperty("SPECIFIC_PROXY_SERVICE_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + + } + + /** + * Initializer. + * @throws InterruptedException In case of an error + * + */ + @AfterClass + public static void closeIgniteNode() throws InterruptedException { + System.out.println("Closing Ignite Node ... "); + + log.info("Stopping already running Apache Ignite nodes ... "); + Ignition.stopAll(true); + Thread.sleep(1000); + + } + + /** + * Test reseter. + * + */ + @After + public void cleanJvmState() throws NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException { + final Field field = LogMessageProviderFactory.class.getDeclaredField("internalMessager"); + field.setAccessible(true); + field.set(null, new DummyStatusMessager()); + + System.clearProperty("eidas.ms.configuration"); + SpringBootApplicationInitializer.exit(); + + } + + + @Test + public void validConfigLocation() throws Throwable { + SpringBootApplicationInitializer + .main(new String[] { + "--spring.config.location=src/test/resources/config/junit_config_2_springboot.properties,classpath:/application.properties", + "--spring.profiles.active=jUnitTestMode" }); + + System.out.println("Is started!"); + + // test Spring-Actuator http Basic-Auth + testSpringActuatorSecurity(); + + } + + private void testSpringActuatorSecurity() throws ClientProtocolException, IOException { + // check if authentication works on actuator end-point + final HttpClientBuilder builder = HttpClients.custom(); + final CloseableHttpClient client = builder.build(); + Assert.assertNotNull("httpClient", client); + + final HttpUriRequest httpGetInfo = new HttpGet("http://localhost:8080/ms_connector/actuator/info"); + final CloseableHttpResponse httpRespInfo = client.execute(httpGetInfo); + Assert.assertEquals("http statusCode", 200, httpRespInfo.getStatusLine().getStatusCode()); + + final HttpUriRequest httpGetHealth = new HttpGet("http://localhost:8080/ms_connector/actuator/health"); + final CloseableHttpResponse httpRespHealth = client.execute(httpGetHealth); + Assert.assertEquals("http statusCode", 503, httpRespHealth.getStatusLine().getStatusCode()); + + } + +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/MainClassWebAppModeTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/MainClassWebAppModeTest.java new file mode 100644 index 00000000..07ef4968 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/MainClassWebAppModeTest.java @@ -0,0 +1,134 @@ +package at.asitplus.eidas.specific.connector.test; + +import java.io.IOException; +import java.lang.reflect.Field; + +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.ignite.Ignition; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.BlockJUnit4ClassRunner; + +import at.asitplus.eidas.specific.connector.SpringBootApplicationInitializer; +import at.gv.egiz.eaaf.core.impl.logging.DummyStatusMessager; +import at.gv.egiz.eaaf.core.impl.logging.LogMessageProviderFactory; + +@RunWith(BlockJUnit4ClassRunner.class) +public class MainClassWebAppModeTest { + + /** + * jUnit class initializer. + * + */ + @BeforeClass + public static void classInitializer() { + final String current = new java.io.File(".").toURI().toString(); + + //eIDAS Ref. Impl. properties + System.setProperty("EIDAS_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + System.setProperty("SPECIFIC_CONNECTOR_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + System.setProperty("SPECIFIC_PROXY_SERVICE_CONFIG_REPOSITORY", current.substring("file:".length()) + + "../basicConfig/eIDAS/"); + + } + + /** + * Initializer. + * + */ + @AfterClass + public static void closeIgniteNode() { + System.out.println("Closing Ignite Node ... "); + Ignition.stopAll(true); + + } + + /** + * Test reseter. + * + */ + @After + public void cleanJvmState() throws NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException { + final Field field = LogMessageProviderFactory.class.getDeclaredField("internalMessager"); + field.setAccessible(true); + field.set(null, new DummyStatusMessager()); + + System.clearProperty("eidas.ms.configuration"); + SpringBootApplicationInitializer.exit(); + + } + + @Test + public void wrongConfigLocation() throws Throwable { + //MS-specific connector property + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/notextist.properties"); + + try { + //starting application + SpringBootApplicationInitializer + .main(new String[] { + "--spring.profiles.active=jUnitTestMode" }); + Assert.fail("Missing configuration not detected"); + + } catch (final Exception e) { + Assert.assertNotNull("Exception is null", e); + + } + } + + + @Test + public void systemdConfigLocation() throws Throwable { + //MS-specific connector property + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/junit_config_1_springboot.properties"); + + //starting application + SpringBootApplicationInitializer + .main(new String[] { + "--spring.profiles.active=jUnitTestMode,springBoot" }); + + System.out.println("Is started!"); + + // test Spring-Actuator http Basic-Auth + testSpringActuatorSecurity(); + + + + + } + + private void testSpringActuatorSecurity() throws ClientProtocolException, IOException { + // check if authentication works on actuator end-point + final HttpClientBuilder builder = HttpClients.custom(); + final CloseableHttpClient client = builder.build(); + Assert.assertNotNull("httpClient", client); + + final HttpUriRequest httpGetInfo = new HttpGet("http://localhost:8080/ms_connector/actuator/info"); + final CloseableHttpResponse httpRespInfo = client.execute(httpGetInfo); + Assert.assertEquals("http statusCode", 200, httpRespInfo.getStatusLine().getStatusCode()); + + + final HttpUriRequest httpGetHealth = new HttpGet("http://localhost:8080/ms_connector/actuator/health"); + final CloseableHttpResponse httpRespHealth = client.execute(httpGetHealth); + Assert.assertEquals("http statusCode", 503, httpRespHealth.getStatusLine().getStatusCode()); + + } + +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java index b7c6cd44..5c0a1420 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/AuthBlockAttributeBuilderTest.java @@ -2,6 +2,8 @@ package at.asitplus.eidas.specific.connector.test.attributes; import static at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions.EID_AUTHBLOCK_SIGNED_NAME; +import java.util.Base64; + import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -13,6 +15,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import at.asitplus.eidas.specific.connector.attributes.AuthBlockAttributeBuilder; import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; @@ -42,6 +45,19 @@ public class AuthBlockAttributeBuilderTest extends AbstractAttributeBuilderTest } @Test + public void checkName() { + Assert.assertEquals("Wrong attr. name", + ExtendedPvpAttributeDefinitions.EID_AUTHBLOCK_SIGNED_NAME, attrBuilde.getName()); + + } + + @Test + public void checkEmptyAttribute() { + Assert.assertNull("empty attr.", attrBuilde.buildEmpty(gen)); + + } + + @Test public void okTest() { log.info("starting: " + mTestName); try { @@ -50,7 +66,8 @@ public class AuthBlockAttributeBuilderTest extends AbstractAttributeBuilderTest final String value = attrBuilde.build(spConfig, authData, gen); - Assert.assertEquals("Authblock build wrong", JSW, value); + Assert.assertNotNull("AuthBlock", value); + Assert.assertEquals("Authblock build wrong", JSW, new String(Base64.getDecoder().decode(value))); } catch (final Exception e) { Assert.assertNull("Attr. builder has an exception", e); diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java index 254efb59..9a2c6cdc 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/attributes/EidasBindAttributeBuilderTest.java @@ -1,13 +1,7 @@ package at.asitplus.eidas.specific.connector.test.attributes; -import at.asitplus.eidas.specific.connector.attributes.EidasBindAttributeBuilder; -import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; -import at.gv.egiz.eaaf.core.impl.idp.auth.attributes.AbstractAttributeBuilderTest; -import lombok.extern.slf4j.Slf4j; +import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.EIDAS_BIND; + import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -17,7 +11,14 @@ import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants.EIDAS_BIND; +import at.asitplus.eidas.specific.connector.attributes.EidasBindAttributeBuilder; +import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; +import at.gv.egiz.eaaf.core.impl.idp.auth.attributes.AbstractAttributeBuilderTest; +import lombok.extern.slf4j.Slf4j; @Slf4j @@ -36,6 +37,19 @@ public class EidasBindAttributeBuilderTest extends AbstractAttributeBuilderTest } @Test + public void checkName() { + Assert.assertEquals("Wrong attr. name", + ExtendedPvpAttributeDefinitions.EID_EIDBIND_NAME, attrBuilde.getName()); + + } + + @Test + public void checkEmptyAttribute() { + Assert.assertNull("empty attr.", attrBuilde.buildEmpty(gen)); + + } + + @Test public void okTest() { log.info("starting: " + mTestName); try { diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/config/BasicConfigurationTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/config/BasicConfigurationTest.java new file mode 100644 index 00000000..80307ea2 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/config/BasicConfigurationTest.java @@ -0,0 +1,137 @@ +package at.asitplus.eidas.specific.connector.test.config; + +import java.net.MalformedURLException; +import java.net.URL; +import java.security.cert.CertificateException; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.config.InitializationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +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 at.asitplus.eidas.specific.connector.config.ServiceProviderConfiguration; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +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 net.shibboleth.utilities.java.support.component.ComponentInitializationException; + +@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" }) +@WebAppConfiguration +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) +@ActiveProfiles(profiles = {"deprecatedConfig"}) +public class BasicConfigurationTest { + + @Autowired private IConfigurationWithSP basicConfig; + + /** + * jUnit class initializer. + * @throws ComponentInitializationException In case of an error + * @throws InitializationException In case of an error + * @throws CertificateException + * + */ + @BeforeClass + public static void classInitializer() throws InitializationException, + ComponentInitializationException, CertificateException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_1.properties"); + + } + + + @Test + public void basicConfig() throws MalformedURLException, EaafException { + Assert.assertEquals("validate req. URL", "http://localhost", + basicConfig.validateIdpUrl(new URL("http://junit/test"))); + + Assert.assertEquals("validate req. URL", "http://localhost", + basicConfig.validateIdpUrl(new URL("http://localhost/test1/test"))); + + } + + @Test + public void loadSpNotExist() throws EaafConfigurationException { + //check + ISpConfiguration sp = basicConfig.getServiceProviderConfiguration( + "https://not/exist"); + + //validate state + Assert.assertNull("spConfig", sp); + + + } + + @Test + public void loadSpDefault() throws EaafConfigurationException { + //check + ISpConfiguration sp = basicConfig.getServiceProviderConfiguration( + "https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/metadata"); + + //validate state + Assert.assertNotNull("spConfig", sp); + Assert.assertEquals("BaseId transfare restrication", true, sp.hasBaseIdTransferRestriction()); + Assert.assertEquals("BaseId process restrication", false, sp.hasBaseIdInternalProcessingRestriction()); + + Assert.assertEquals("req. LoA size", 1, sp.getRequiredLoA().size()); + Assert.assertEquals("req. LoA", EaafConstants.EIDAS_LOA_HIGH, sp.getRequiredLoA().get(0)); + Assert.assertEquals("LoA matching mode", + EaafConstants.EIDAS_LOA_MATCHING_MINIMUM, sp.getLoAMatchingMode()); + + } + + @Test + public void loadSpNoBaseIdTransferRestriction() throws EaafException { + //check + ServiceProviderConfiguration sp = basicConfig.getServiceProviderConfiguration( + "https://demo.egiz.gv.at/demoportal_moaid-2.0/sp/eidas/metadata", ServiceProviderConfiguration.class); + + //validate state + Assert.assertNotNull("spConfig", sp); + Assert.assertNull("bPKTarget already set", sp.getAreaSpecificTargetIdentifier()); + + //validate baseId transfer restriction + sp.setBpkTargetIdentifier(EaafConstants.URN_PREFIX_CDID + "ZP"); + Assert.assertEquals("BaseId restrication", false, sp.hasBaseIdTransferRestriction()); + Assert.assertEquals("bPKTarget", EaafConstants.URN_PREFIX_CDID + "ZP", sp.getAreaSpecificTargetIdentifier()); + + sp.setBpkTargetIdentifier(EaafConstants.URN_PREFIX_WBPK_TARGET_WITH_X + "FN+123456h"); + Assert.assertEquals("BaseId restrication", true, sp.hasBaseIdTransferRestriction()); + + } + + @Test + public void loadSpWithMsSpecificConfig() throws EaafConfigurationException { + //check + ServiceProviderConfiguration sp = basicConfig.getServiceProviderConfiguration( + "https://demo.egiz.gv.at/junit_test", ServiceProviderConfiguration.class); + + //validate state + Assert.assertNotNull("spConfig", sp); + Assert.assertEquals("friendlyName", "jUnit test", sp.getFriendlyName()); + Assert.assertEquals("UniqueId", "https://demo.egiz.gv.at/junit_test", sp.getUniqueIdentifier()); + Assert.assertEquals("BaseId restrication", true, sp.hasBaseIdTransferRestriction()); + Assert.assertEquals("generic config value", false, + sp.isConfigurationValue("policy.allowed.requested.targets")); + Assert.assertEquals("generic config value", "test", + sp.getConfigurationValue("policy.allowed.requested.targets")); + Assert.assertEquals("not_exist_value", "true", sp.getConfigurationValue("not.exist", "true")); + + } +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/controller/ProcessEngineSignalControllerTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/controller/ProcessEngineSignalControllerTest.java new file mode 100644 index 00000000..d2c4aff2 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/controller/ProcessEngineSignalControllerTest.java @@ -0,0 +1,77 @@ +package at.asitplus.eidas.specific.connector.test.controller; + +import java.io.IOException; +import java.net.URISyntaxException; + +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.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 at.asitplus.eidas.specific.connector.controller.ProcessEngineSignalController; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; + +@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" }) +@ActiveProfiles(profiles = {"deprecatedConfig"}) +@WebAppConfiguration +public class ProcessEngineSignalControllerTest { + + @Autowired private ProcessEngineSignalController controller; + + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + + @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 setUp() throws EaafStorageException, URISyntaxException { + httpReq = new MockHttpServletRequest("POST", "https://localhost/authhandler"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + } + + @Test + public void noPendingRequestId() throws IOException, EaafException { + //set-up + + //execute test + controller.performGenericAuthenticationProcess(httpReq, httpResp); + + //validate state + Assert.assertEquals("http StatusCode", 302, httpResp.getStatus()); + Assert.assertNotNull("redirect header", httpResp.getHeaderValue("Location")); + Assert.assertTrue("wrong redirect header", + httpResp.getHeader("Location").startsWith("http://localhost/errorHandling?errorid=")); + + } + + +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/health/EidasNodeMetadataHealthIndicatorNoEndpointTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/health/EidasNodeMetadataHealthIndicatorNoEndpointTest.java new file mode 100644 index 00000000..b04a5bdb --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/health/EidasNodeMetadataHealthIndicatorNoEndpointTest.java @@ -0,0 +1,70 @@ +package at.asitplus.eidas.specific.connector.test.health; + +import java.io.IOException; + +import org.apache.commons.io.IOUtils; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.health.Health; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import at.asitplus.eidas.specific.connector.health.EidasNodeMetadataHealthIndicator; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ + "/spring/SpringTest-context_healthcheck.xml" }) +@TestPropertySource(locations = {"classpath:/config/junit_config_2_springboot.properties"}) +@WebAppConfiguration +public class EidasNodeMetadataHealthIndicatorNoEndpointTest { + + @Autowired EidasNodeMetadataHealthIndicator health; + + private static MockWebServer mockWebServer = null; + + /** + * Testclass initializer. + * + * @throws IOException In case of an error + */ + @BeforeClass + public static void classInitializer() throws IOException { + mockWebServer = new MockWebServer(); + mockWebServer.start(40900); + mockWebServer.url("/mockup"); + + } + + @AfterClass + public static void resetTestEnviroment() throws NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException, IOException { + mockWebServer.shutdown(); + + } + + @Test + public void noEndpointInConfiguration() throws IOException { + //set-up status + mockWebServer.enqueue(new MockResponse().setResponseCode(200) + .setBody(IOUtils.toString(EidasNodeMetadataHealthIndicatorNoEndpointTest.class + .getResourceAsStream("/config/log4j.properties"), "UTF-8")) + .setHeader("Content-Type", MediaType.APPLICATION_XML)); + + //perform test + Health status = health.health(); + + //validate state + Assert.assertEquals("wrong healthState", Health.unknown().build().getStatus(), status.getStatus()); + + } + +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/health/EidasNodeMetadataHealthIndicatorTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/health/EidasNodeMetadataHealthIndicatorTest.java new file mode 100644 index 00000000..b044d4d2 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/health/EidasNodeMetadataHealthIndicatorTest.java @@ -0,0 +1,102 @@ +package at.asitplus.eidas.specific.connector.test.health; + +import java.io.IOException; + +import org.apache.commons.io.IOUtils; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.health.Health; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import at.asitplus.eidas.specific.connector.health.EidasNodeMetadataHealthIndicator; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ + "/spring/SpringTest-context_healthcheck.xml" }) +@TestPropertySource(locations = {"classpath:/config/junit_config_1_springboot.properties"}) +@WebAppConfiguration +public class EidasNodeMetadataHealthIndicatorTest { + + @Autowired EidasNodeMetadataHealthIndicator health; + + private static MockWebServer mockWebServer = null; + + /** + * Testclass initializer. + * + * @throws IOException In case of an error + */ + @BeforeClass + public static void classInitializer() throws IOException { + mockWebServer = new MockWebServer(); + mockWebServer.start(40900); + mockWebServer.url("/mockup"); + + } + + @AfterClass + public static void resetTestEnviroment() throws NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException, IOException { + mockWebServer.shutdown(); + + } + + @Test + public void httpStatusCode500() throws IOException { + //set-up status + mockWebServer.enqueue(new MockResponse().setResponseCode(500) + .setBody(IOUtils.toString(EidasNodeMetadataHealthIndicatorTest.class + .getResourceAsStream("/data/metadata_valid.xml"), "UTF-8")) + .setHeader("Content-Type", MediaType.APPLICATION_XML)); + + //perform test + Health status = health.health(); + + //validate state + Assert.assertEquals("wrong healthState", Health.down().build().getStatus(), status.getStatus()); + + } + + @Test + public void httpStatusCode200() throws IOException { + //set-up status + mockWebServer.enqueue(new MockResponse().setResponseCode(200) + .setBody(IOUtils.toString(EidasNodeMetadataHealthIndicatorTest.class + .getResourceAsStream("/data/metadata_valid.xml"), "UTF-8")) + .setHeader("Content-Type", MediaType.APPLICATION_XML)); + + //perform test + Health status = health.health(); + + //validate state + Assert.assertEquals("wrong healthState", Health.up().build().getStatus(), status.getStatus()); + + } + + @Test + public void noXmlResponse() throws IOException { + //set-up status + mockWebServer.enqueue(new MockResponse().setResponseCode(200) + .setBody(IOUtils.toString(EidasNodeMetadataHealthIndicatorTest.class + .getResourceAsStream("/config/log4j.properties"), "UTF-8")) + .setHeader("Content-Type", MediaType.APPLICATION_XML)); + + //perform test + Health status = health.health(); + + //validate state + Assert.assertEquals("wrong healthState", Health.down().build().getStatus(), status.getStatus()); + + } + +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/saml2/Pvp2SProfileEndPointTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/saml2/Pvp2SProfileEndPointTest.java new file mode 100644 index 00000000..bcba3e11 --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/saml2/Pvp2SProfileEndPointTest.java @@ -0,0 +1,337 @@ +package at.asitplus.eidas.specific.connector.test.saml2; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Timer; + +import javax.xml.transform.TransformerException; + +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.opensaml.core.config.InitializationException; +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.metadata.resolver.impl.ResourceBackedMetadataResolver; +import org.opensaml.saml.saml2.core.RequestAbstractType; +import org.opensaml.saml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; +import org.opensaml.security.credential.Credential; +import org.opensaml.security.x509.BasicX509Credential; +import org.opensaml.xmlsec.signature.support.SignatureException; +import org.opensaml.xmlsec.signature.support.SignatureValidator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ResourceLoader; +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.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.util.Base64Utils; +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.controller.Pvp2SProfileEndpoint; +import at.asitplus.eidas.specific.connector.provider.PvpEndPointCredentialProvider; +import at.asitplus.eidas.specific.connector.provider.PvpMetadataProvider; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.IRequestStorage; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.OpenSaml3ResourceAdapter; +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.component.ComponentInitializationException; +import net.shibboleth.utilities.java.support.xml.XMLParserException; + +@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" }) +@ActiveProfiles(profiles = {"deprecatedConfig"}) +@WebAppConfiguration +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) +public class Pvp2SProfileEndPointTest { + + + @Autowired private Pvp2SProfileEndpoint controller; + @Autowired private PvpEndPointCredentialProvider credentialProvider; + @Autowired private PvpMetadataProvider metadataProvider; + @Autowired private ResourceLoader resourceLoader; + @Autowired private IRequestStorage storage; + + private static CertificateFactory fact; + + + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + + + /** + * jUnit class initializer. + * @throws ComponentInitializationException In case of an error + * @throws InitializationException In case of an error + * @throws CertificateException + * + */ + @BeforeClass + public static void classInitializer() throws InitializationException, + ComponentInitializationException, CertificateException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + "src/test/resources/config/junit_config_1.properties"); + + EaafOpenSaml3xInitializer.eaafInitialize(); + + fact = CertificateFactory.getInstance("X.509"); + + } + + /** + * jUnit test set-up. + * @throws EaafException + * + */ + @Before + public void initialize() throws EaafException { + httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + } + + @Test + public void authnReqWrongEndpoint() throws EaafException, XMLParserException, UnmarshallingException, + UnsupportedEncodingException, TransformerException, IOException, MarshallingException, + ComponentInitializationException { + //initialize test + final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + Pvp2SProfileEndPointTest.class.getResourceAsStream("/data/pvp2_authn_3.xml")); + authnReq.setIssueInstant(DateTime.now()); + RequestAbstractType signedAuthnReq = + Saml2Utils.signSamlObject(authnReq, credentialProvider.getMetaDataSigningCredential(), true); + String b64 = Base64Utils.encodeToString(DomUtils.serializeNode( + XMLObjectSupport.getMarshaller(signedAuthnReq).marshall(signedAuthnReq)).getBytes("UTF-8")); + httpReq.setParameter("SAMLRequest", b64); + + final org.springframework.core.io.Resource resource = resourceLoader.getResource( + "classpath:/data/metadata_valid.xml"); + Timer timer = new Timer("PVP metadata-resolver refresh"); + ResourceBackedMetadataResolver fileSystemResolver = + new ResourceBackedMetadataResolver(timer, new OpenSaml3ResourceAdapter(resource)); + fileSystemResolver.setId("test"); + fileSystemResolver.setParserPool(XMLObjectProviderRegistrySupport.getParserPool()); + fileSystemResolver.initialize(); + metadataProvider.addMetadataResolverIntoChain(fileSystemResolver); + + + //request SAML2 authentication + try { + controller.pvpIdpPostRequest(httpReq, httpResp); + Assert.fail("wrong AuthnRequest not detected"); + + }catch (EaafException e) { + Assert.assertEquals("wrong errorId", "pvp2.22", e.getErrorId()); + + } + } + + @Test + public void authnReqWrongSigned() throws EaafException, XMLParserException, UnmarshallingException, + UnsupportedEncodingException, TransformerException, IOException, MarshallingException, + ComponentInitializationException { + //initialize test + final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + Pvp2SProfileEndPointTest.class.getResourceAsStream("/data/pvp2_authn_1.xml")); + authnReq.setIssueInstant(DateTime.now()); + RequestAbstractType signedAuthnReq = + Saml2Utils.signSamlObject(authnReq, credentialProvider.getMetaDataSigningCredential(), true); + String b64 = Base64Utils.encodeToString(DomUtils.serializeNode( + XMLObjectSupport.getMarshaller(signedAuthnReq).marshall(signedAuthnReq)).getBytes("UTF-8")); + httpReq.setParameter("SAMLRequest", b64); + + final org.springframework.core.io.Resource resource = resourceLoader.getResource( + "classpath:/data/metadata_valid.xml"); + Timer timer = new Timer("PVP metadata-resolver refresh"); + ResourceBackedMetadataResolver fileSystemResolver = + new ResourceBackedMetadataResolver(timer, new OpenSaml3ResourceAdapter(resource)); + fileSystemResolver.setId("test"); + fileSystemResolver.setParserPool(XMLObjectProviderRegistrySupport.getParserPool()); + fileSystemResolver.initialize(); + metadataProvider.addMetadataResolverIntoChain(fileSystemResolver); + + + //request SAML2 authentication + try { + controller.pvpIdpPostRequest(httpReq, httpResp); + Assert.fail("wrong AuthnRequest not detected"); + + }catch (EaafException e) { + Assert.assertEquals("wrong errorId", "pvp2.21", e.getErrorId()); + + } + } + + @Test + public void authnReqMetadataExpired() throws EaafException, XMLParserException, UnmarshallingException, + UnsupportedEncodingException, TransformerException, IOException, MarshallingException, + ComponentInitializationException { + //initialize test + final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + Pvp2SProfileEndPointTest.class.getResourceAsStream("/data/pvp2_authn_1.xml")); + authnReq.setIssueInstant(DateTime.now()); + RequestAbstractType signedAuthnReq = + Saml2Utils.signSamlObject(authnReq, credentialProvider.getMetaDataSigningCredential(), true); + String b64 = Base64Utils.encodeToString(DomUtils.serializeNode( + XMLObjectSupport.getMarshaller(signedAuthnReq).marshall(signedAuthnReq)).getBytes("UTF-8")); + httpReq.setParameter("SAMLRequest", b64); + + final org.springframework.core.io.Resource resource = resourceLoader.getResource( + "classpath:/data/metadata_expired.xml"); + Timer timer = new Timer("PVP metadata-resolver refresh"); + ResourceBackedMetadataResolver fileSystemResolver = + new ResourceBackedMetadataResolver(timer, new OpenSaml3ResourceAdapter(resource)); + fileSystemResolver.setId("test"); + fileSystemResolver.setParserPool(XMLObjectProviderRegistrySupport.getParserPool()); + fileSystemResolver.initialize(); + metadataProvider.addMetadataResolverIntoChain(fileSystemResolver); + + + //request SAML2 authentication + try { + controller.pvpIdpPostRequest(httpReq, httpResp); + Assert.fail("wrong AuthnRequest not detected"); + + }catch (EaafException e) { + Assert.assertEquals("wrong errorId", "pvp2.21", e.getErrorId()); + + } + } + + @Test + public void authnReqValid() throws EaafException, XMLParserException, UnmarshallingException, + UnsupportedEncodingException, TransformerException, IOException, MarshallingException, + ComponentInitializationException { + //initialize test + final RequestAbstractType authnReq = (RequestAbstractType) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + Pvp2SProfileEndPointTest.class.getResourceAsStream("/data/pvp2_authn_1.xml")); + authnReq.setIssueInstant(DateTime.now()); + RequestAbstractType signedAuthnReq = + Saml2Utils.signSamlObject(authnReq, credentialProvider.getMessageSigningCredential(), true); + String b64 = Base64Utils.encodeToString(DomUtils.serializeNode( + XMLObjectSupport.getMarshaller(signedAuthnReq).marshall(signedAuthnReq)).getBytes("UTF-8")); + httpReq.setParameter("SAMLRequest", b64); + + final org.springframework.core.io.Resource resource = resourceLoader.getResource( + "classpath:/data/metadata_valid.xml"); + Timer timer = new Timer("PVP metadata-resolver refresh"); + ResourceBackedMetadataResolver fileSystemResolver = + new ResourceBackedMetadataResolver(timer, new OpenSaml3ResourceAdapter(resource)); + fileSystemResolver.setId("test"); + fileSystemResolver.setParserPool(XMLObjectProviderRegistrySupport.getParserPool()); + fileSystemResolver.initialize(); + metadataProvider.addMetadataResolverIntoChain(fileSystemResolver); + + + //request SAML2 authentication + controller.pvpIdpPostRequest(httpReq, httpResp); + + + //validate state + Assert.assertEquals("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("Wrong page", html.contains("action=\"/myHomeCountry\"")); + + String pattern = "<input type=\"hidden\" name=\"pendingid\" value=\""; + int pendingIdStart = html.indexOf(pattern) + pattern.length(); + int pendingIdEnd = html.indexOf("\"", pendingIdStart); + String pendingReqId = html.substring(pendingIdStart, pendingIdEnd); + Assert.assertFalse("pendingReqId is empty", pendingReqId.isEmpty()); + + IRequest pendingReq = storage.getPendingRequest(pendingReqId); + Assert.assertNotNull("pendingReq", pendingReq); + Assert.assertNotNull("piiTransId", pendingReq.getUniquePiiTransactionIdentifier()); + Assert.assertNotNull("piiTransId", pendingReq.getUniqueTransactionIdentifier()); + + Assert.assertEquals("wrong OA Id", "https://demo.egiz.gv.at/demoportal-openID_demo", + pendingReq.getRawData(MsEidasNodeConstants.DATA_REQUESTERID, String.class)); + Assert.assertEquals("wrong bPK Target", "urn:publicid:gv.at:cdid+BF", + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + + + } + + @Test + public void checkSaml2Metadata() throws EaafException, UnsupportedEncodingException, XMLParserException, + UnmarshallingException, CertificateException, SignatureException { + + //request SAML2 Metadata + controller.pvpMetadataRequest(httpReq, httpResp); + + //validate state + Assert.assertEquals("http statuscode", 200, httpResp.getStatus()); + Assert.assertEquals("Wrong http ContentType", "application/xml", httpResp.getContentType()); + + String html = httpResp.getContentAsString(); + Assert.assertNotNull("html result is null", html); + Assert.assertFalse("html result is empty", html.isEmpty()); + + + final EntityDescriptor entity = (EntityDescriptor) XMLObjectSupport.unmarshallFromInputStream( + XMLObjectProviderRegistrySupport.getParserPool(), + new ByteArrayInputStream(html.getBytes("UTF-8"))); + + Assert.assertNotNull("Unmarshalling failed", entity); + Assert.assertNotNull("EntityId is null", entity.getEntityID()); + + Assert.assertNotNull("Signature is null", entity.getSignature()); + final SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); + sigValidator.validate(entity.getSignature()); + + final Credential cred = new BasicX509Credential((X509Certificate) fact.generateCertificate( + Pvp2SProfileEndPointTest.class.getResourceAsStream("/config/keys/Metadata.pem"))); + SignatureValidator.validate(entity.getSignature(), cred); + + Assert.assertEquals("wrong entityId", "http://localhost/pvp/metadata", entity.getEntityID()); + Assert.assertNotNull("IDPSSODescr", entity.getRoleDescriptors(IDPSSODescriptor.DEFAULT_ELEMENT_NAME)); + Assert.assertNotNull("SPSSODescr", entity.getRoleDescriptors(SPSSODescriptor.DEFAULT_ELEMENT_NAME)); + Assert.assertEquals("SPSSODescr. size", 0, + entity.getRoleDescriptors(SPSSODescriptor.DEFAULT_ELEMENT_NAME).size()); + + List<RoleDescriptor> idp = entity.getRoleDescriptors(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + Assert.assertEquals("IDP descr. size", 1, idp.size()); + Assert.assertEquals("IDP descr. endpoints", 2, idp.get(0).getEndpoints().size()); + Assert.assertEquals("IDP descr. keyDescr", 1, idp.get(0).getKeyDescriptors().size()); + + } + +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java index 9d590055..4bff9416 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/EvaluateCountrySelectionTaskTest.java @@ -12,6 +12,7 @@ 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; @@ -34,6 +35,7 @@ import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; "/eaaf_pvp.beans.xml", "/eaaf_pvp_idp.beans.xml", "/spring/SpringTest-context_simple_storage.xml" }) +@ActiveProfiles(profiles = {"deprecatedConfig"}) @WebAppConfiguration public class EvaluateCountrySelectionTaskTest { diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java index 2a1d7cd4..d902f758 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/task/GenerateCountrySelectionFrameTaskTest.java @@ -13,6 +13,7 @@ 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; @@ -32,6 +33,7 @@ import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; "/eaaf_pvp.beans.xml", "/eaaf_pvp_idp.beans.xml", "/spring/SpringTest-context_simple_storage.xml" }) +@ActiveProfiles(profiles = {"deprecatedConfig"}) @WebAppConfiguration public class GenerateCountrySelectionFrameTaskTest { diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/utils/AuthenticationDataBuilderTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/utils/AuthenticationDataBuilderTest.java new file mode 100644 index 00000000..5f1c5dcf --- /dev/null +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/utils/AuthenticationDataBuilderTest.java @@ -0,0 +1,354 @@ +package at.asitplus.eidas.specific.connector.test.utils; + +import static at.asitplus.eidas.specific.connector.MsEidasNodeConstants.PROP_CONFIG_SP_NEW_EID_MODE; + +import java.io.IOException; +import java.security.PublicKey; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.transform.TransformerException; + +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.config.InitializationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.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 org.w3c.dom.Element; + +import at.asitplus.eidas.specific.connector.builder.AuthenticationDataBuilder; +import at.asitplus.eidas.specific.modules.auth.eidas.v2.Constants; +import at.gv.egiz.eaaf.core.api.data.EaafConfigConstants; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.data.ExtendedPvpAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.data.PvpAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +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.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; +import at.gv.egiz.eaaf.core.exceptions.EaafParserException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafOpenSaml3xInitializer; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/applicationContext.xml", "/spring/SpringTest_connector.beans.xml", "/eaaf_core.beans.xml", + "/eaaf_pvp.beans.xml", "/eaaf_pvp_idp.beans.xml", "/spring/SpringTest-context_simple_storage.xml" }) +@ActiveProfiles(profiles = {"deprecatedConfig"}) +@WebAppConfiguration +public class AuthenticationDataBuilderTest { + + @Autowired + private AuthenticationDataBuilder authenticationDataBuilder; + + @Autowired(required = true) + private IConfiguration basicConfig; + + private MockHttpServletRequest httpReq; + private MockHttpServletResponse httpResp; + private TestRequestImpl pendingReq; + + private DummySpConfiguration oaParam; + + private String eidasBind; + private String authBlock; + + @BeforeClass + public static void classInitializer() throws InitializationException, ComponentInitializationException { + final String current = new java.io.File(".").toURI().toString(); + System.setProperty("eidas.ms.configuration", current + + "src/test/resources/config/junit_config_3.properties"); + + EaafOpenSaml3xInitializer.eaafInitialize(); + } + + @Before + public void initialize() throws EaafStorageException { + httpReq = new MockHttpServletRequest("POST", "https://localhost/ms_connector"); + httpResp = new MockHttpServletResponse(); + RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpReq, httpResp)); + + final Map<String, String> 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 DummySpConfiguration(spConfig, basicConfig); + + pendingReq = new TestRequestImpl(); + pendingReq.setAuthUrl("https://localhost/ms_connector"); + pendingReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(10)); + pendingReq.setPiiTransactionId(RandomStringUtils.randomAlphanumeric(10)); + pendingReq.setSpConfig(oaParam); + authBlock = RandomStringUtils.randomAlphanumeric(20); + eidasBind = RandomStringUtils.randomAlphanumeric(20); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.SZR_AUTHBLOCK, authBlock); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .setGenericDataToSession(Constants.EIDAS_BIND, eidasBind); + pendingReq.getSessionData(AuthProcessDataWrapper.class) + .setQaaLevel(EaafConstants.EIDAS_LOA_PREFIX + RandomStringUtils.randomAlphabetic(5)); + pendingReq.getSessionData(AuthProcessDataWrapper.class).setGenericDataToSession( + PvpAttributeDefinitions.EID_ISSUING_NATION_NAME, + RandomStringUtils.randomAlphabetic(2)); + + LocaleContextHolder.resetLocaleContext(); + + } + + @Test + public void eidMode() throws EaafAuthenticationException { + // initialize state + pendingReq.getSessionData(AuthProcessDataWrapper.class).setEidProcess(true); + + // execute + IAuthData authData = authenticationDataBuilder.buildAuthenticationData(pendingReq); + + // validate state + Assert.assertNotNull("AuthData null", authData); + Assert.assertNotNull("authBlock null", authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class)); + Assert.assertNotNull("eidasBind null", authData.getGenericData(Constants.EIDAS_BIND, String.class)); + Assert.assertNotNull("LoA null", authData.getEidasQaaLevel()); + + String authBlock = authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class); + String eidasBind = authData.getGenericData(Constants.EIDAS_BIND, String.class); + + Assert.assertEquals("authBlock not equal", this.authBlock, authBlock); + Assert.assertEquals("eidasBind not equal", this.eidasBind, eidasBind); + Assert.assertEquals("piiTransactionId", + authData.getGenericData(ExtendedPvpAttributeDefinitions.EID_PII_TRANSACTION_ID_NAME, String.class), + this.pendingReq.getUniquePiiTransactionIdentifier()); + Assert.assertNotNull("assertion validTo", authData.getSsoSessionValidTo()); + Assert.assertEquals("LoA", pendingReq.getSessionData(AuthProcessDataWrapper.class).getQaaLevel(), + authData.getEidasQaaLevel()); + Assert.assertEquals("EID-ISSUING-NATION", + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession( + PvpAttributeDefinitions.EID_ISSUING_NATION_NAME), + authData.getCiticenCountryCode()); + + Assert.assertNull("bPK", authData.getBpk()); + Assert.assertNull("bPKType", authData.getBpkType()); + Assert.assertNull("FamilyName", authData.getFamilyName()); + Assert.assertNull("GivenName", authData.getGivenName()); + Assert.assertNull("DateOfBirth", authData.getDateOfBirth()); + Assert.assertNull("baseId", authData.getIdentificationValue()); + Assert.assertNull("baseIdType", authData.getIdentificationType()); + Assert.assertNull("IDL", authData.getIdentityLink()); + + } + + @Test + public void moaIdMode() throws EaafAuthenticationException, EaafBuilderException { + //initialize state + pendingReq.getSessionData(AuthProcessDataWrapper.class).setEidProcess(false); + IIdentityLink idl = buildDummyIdl(); + pendingReq.getSessionData(AuthProcessDataWrapper.class).setIdentityLink(idl); + + //execute + IAuthData authData = authenticationDataBuilder.buildAuthenticationData(pendingReq); + + //validate state + Assert.assertNotNull("AuthData null", authData); + Assert.assertNull("authBlock null", authData.getGenericData(Constants.SZR_AUTHBLOCK, String.class)); + Assert.assertNull("eidasBind null", authData.getGenericData(Constants.EIDAS_BIND, String.class)); + Assert.assertNull("piiTransactionId", + authData.getGenericData(ExtendedPvpAttributeDefinitions.EID_PII_TRANSACTION_ID_NAME, String.class)); + + + Assert.assertNotNull("assertion validTo", authData.getSsoSessionValidTo()); + Assert.assertNotNull("LoA null", authData.getEidasQaaLevel()); + Assert.assertEquals("LoA", pendingReq.getSessionData(AuthProcessDataWrapper.class).getQaaLevel(), + authData.getEidasQaaLevel()); + Assert.assertEquals("EID-ISSUING-NATION", + pendingReq.getSessionData(AuthProcessDataWrapper.class).getGenericDataFromSession( + PvpAttributeDefinitions.EID_ISSUING_NATION_NAME), + authData.getCiticenCountryCode()); + + Assert.assertEquals("FamilyName", idl.getFamilyName(), authData.getFamilyName()); + Assert.assertEquals("GivenName", idl.getGivenName(), authData.getGivenName()); + Assert.assertEquals("DateOfBirth", idl.getDateOfBirth(), authData.getFormatedDateOfBirth()); + Assert.assertEquals("bPK", + BpkBuilder.generateAreaSpecificPersonIdentifier( + idl.getIdentificationValue(), EaafConstants.URN_PREFIX_CDID + "XX").getFirst(), + authData.getBpk()); + Assert.assertEquals("bPKType", EaafConstants.URN_PREFIX_CDID + "XX", authData.getBpkType()); + Assert.assertNotNull("IDL", authData.getIdentityLink()); + + + } + + private IIdentityLink buildDummyIdl() { + return new IIdentityLink() { + + String familyName = RandomStringUtils.randomAlphabetic(10); + String givenName = RandomStringUtils.randomAlphabetic(10); + String dateOfBirth = "1955-02-03"; + String baseId = RandomStringUtils.randomAlphanumeric(20); + String saml2Serialized = RandomStringUtils.randomAlphanumeric(150); + + + + @Override + public void setSamlAssertion(Element arg0) throws TransformerException, IOException { + + } + + @Override + public void setPublicKey(PublicKey[] arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setPrPerson(Element arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setIssueInstant(String arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setIdentificationValue(String arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setIdentificationType(String arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setGivenName(String arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setFamilyName(String arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setDsigReferenceTransforms(Element[] arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setDateOfBirth(String arg0) { + // TODO Auto-generated method stub + + } + + @Override + public String getSerializedSamlAssertion() { + return this.saml2Serialized; + } + + @Override + public Element getSamlAssertion() { + IIdentityLink fullIdl; + try { + fullIdl = new SimpleIdentityLinkAssertionParser( + AuthenticationDataBuilderTest.class.getResourceAsStream("/data/test_idl_1.xml")).parseIdentityLink(); + return fullIdl.getSamlAssertion(); + + } catch (EaafParserException e) { + e.printStackTrace(); + } + + return null; + + } + + @Override + public PublicKey[] getPublicKey() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Element getPrPerson() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getIssueInstantDate() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getIssueInstant() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getIdentificationValue() { + return this.baseId; + } + + @Override + public String getIdentificationType() { + return EaafConstants.URN_PREFIX_BASEID; + } + + @Override + public String getGivenName() { + return this.givenName; + } + + @Override + public String getFamilyName() { + return this.familyName; + } + + @Override + public Element[] getDsigReferenceTransforms() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDateOfBirth() { + return this.dateOfBirth; + + } + }; + } + +} diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthnRequestValidatorTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/utils/AuthnRequestValidatorTest.java index 389f561e..9aafb4b6 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/AuthnRequestValidatorTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/utils/AuthnRequestValidatorTest.java @@ -1,4 +1,4 @@ -package at.asitplus.eidas.specific.connector.test; +package at.asitplus.eidas.specific.connector.test.utils; import java.io.IOException; import java.util.HashMap; @@ -22,6 +22,7 @@ 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.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @@ -52,6 +53,7 @@ import net.shibboleth.utilities.java.support.component.ComponentInitializationEx "/eaaf_pvp.beans.xml", "/eaaf_pvp_idp.beans.xml", "/spring/SpringTest-context_simple_storage.xml" }) +@ActiveProfiles(profiles = {"deprecatedConfig"}) @WebAppConfiguration @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class AuthnRequestValidatorTest { diff --git a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/CountrySelectionProcessImplTest.java b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/utils/CountrySelectionProcessImplTest.java index 455288f5..d0343eba 100644 --- a/connector/src/test/java/at/asitplus/eidas/specific/connector/test/CountrySelectionProcessImplTest.java +++ b/connector/src/test/java/at/asitplus/eidas/specific/connector/test/utils/CountrySelectionProcessImplTest.java @@ -1,4 +1,4 @@ -package at.asitplus.eidas.specific.connector.test; +package at.asitplus.eidas.specific.connector.test.utils; import java.util.HashMap; import java.util.Map; |