method2testcases stringlengths 118 6.63k |
|---|
### Question:
UnknownMethodAlgorithmLogger { public static void probeAuthnRequestForMethodAlgorithm(final AuthnRequestFromRelyingParty authnRequest) { if (authnRequest != null) { authnRequest.getSignature().ifPresent((signature) -> logMethodAlgorithm(Role.SP, signature, AuthnRequest.DEFAULT_ELEMENT_LOCAL_NAME) ); } } static void probeResponseForMethodAlgorithm(final InboundResponseFromIdp response); static void probeAssertionForMethodAlgorithm(final Assertion assertion, final String typeOfAssertion); static void probeAuthnRequestForMethodAlgorithm(final AuthnRequestFromRelyingParty authnRequest); static final String SIGNATURE_AND_DIGEST_ALGORITHMS_MESSAGE; static final String SIGNATURE_ALGORITHM_MESSAGE; static final String DIGEST_ALGORITHM_MESSAGE; }### Answer:
@Test public void shouldNotReportStrongAlgorithmsInSPAuthnRequest() throws Exception { AuthnRequestFromRelyingParty authnRequestFromRelyingParty = anAuthnRequestFromRelyingParty() .withId(ID) .withIssuer(ISSUER_SP) .withSignature(signature.get()) .build(); UnknownMethodAlgorithmLogger.probeAuthnRequestForMethodAlgorithm(authnRequestFromRelyingParty); verify(mockAppender, times(0)).doAppend(captorLoggingEvent.capture()); }
@Test public void shouldReportUnknownSignatureAlgorithmInSPAuthnRequest() throws Exception { AuthnRequestFromRelyingParty authnRequestFromRelyingParty = anAuthnRequestFromRelyingParty() .withId(ID) .withIssuer(ISSUER_SP) .withSignature(signatureWithUnknownSignatureAlgorithm.get()) .build(); UnknownMethodAlgorithmLogger.probeAuthnRequestForMethodAlgorithm(authnRequestFromRelyingParty); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.SIGNATURE_ALGORITHM_MESSAGE, SP, SIGNATURE_RSA_SHA1_ID, AuthnRequest.DEFAULT_ELEMENT_LOCAL_NAME)); }
@Test public void shouldReportUnknownDigestAlgorithmInSPAuthnRequest() throws Exception { AuthnRequestFromRelyingParty authnRequestFromRelyingParty = anAuthnRequestFromRelyingParty() .withId(ID) .withIssuer(ISSUER_SP) .withSignature(signatureWithUnknownDigestAlgorithm.get()) .build(); UnknownMethodAlgorithmLogger.probeAuthnRequestForMethodAlgorithm(authnRequestFromRelyingParty); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.DIGEST_ALGORITHM_MESSAGE, SP, DIGEST_SHA1_ID, AuthnRequest.DEFAULT_ELEMENT_LOCAL_NAME)); }
@Test public void shouldReportUnknownSignatureAndDigestAlgorithmsInSPAuthnRequest() throws Exception { AuthnRequestFromRelyingParty authnRequestFromRelyingParty = anAuthnRequestFromRelyingParty() .withId(ID) .withIssuer(ISSUER_SP) .withSignature(signatureWithUnknownSignatureAndDigestAlgorithms.get()) .build(); UnknownMethodAlgorithmLogger.probeAuthnRequestForMethodAlgorithm(authnRequestFromRelyingParty); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.SIGNATURE_AND_DIGEST_ALGORITHMS_MESSAGE, SP, SIGNATURE_RSA_SHA1_ID, DIGEST_SHA1_ID, AuthnRequest.DEFAULT_ELEMENT_LOCAL_NAME)); } |
### Question:
HubEncryptionKeyStore implements EncryptionKeyStore { @Override public PublicKey getEncryptionKeyForEntity(String entityId) { LOG.info("Retrieving encryption key for {} from config", entityId); try { return configServiceKeyStore.getEncryptionKeyForEntity(entityId); } catch (ApplicationException e) { if (e.getExceptionType().equals(ExceptionType.CLIENT_ERROR)) { throw new NoKeyConfiguredForEntityException(entityId); } throw new RuntimeException(e); } } @Inject HubEncryptionKeyStore(ConfigServiceKeyStore configServiceKeyStore); @Override PublicKey getEncryptionKeyForEntity(String entityId); }### Answer:
@Test public void shouldGetPublicKeyForAnEntityThatExists() throws Exception { String entityId = "entityId"; when(configServiceKeyStore.getEncryptionKeyForEntity(entityId)).thenReturn(publicKey); final PublicKey key = keyStore.getEncryptionKeyForEntity(entityId); assertThat(key).isEqualTo(publicKey); }
@Test(expected = NoKeyConfiguredForEntityException.class) public void shouldThrowExceptionIfNoPublicKeyForEntityId() throws Exception { String entityId = "non-existent-entity"; when(configServiceKeyStore.getEncryptionKeyForEntity(entityId)).thenThrow(ApplicationException.createUnauditedException(ExceptionType.CLIENT_ERROR, UUID.randomUUID())); keyStore.getEncryptionKeyForEntity(entityId); } |
### Question:
SigningCertFromMetadataExtractor { public X509Certificate getSigningCertForCurrentSigningKey(PublicKey publicSigningKey) { CriteriaSet criteriaSet = new CriteriaSet( new EntityIdCriterion(hubEntityId), new UsageCriterion(UsageType.SIGNING), new ProtocolCriterion(SAMLConstants.SAML20P_NS), new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME), new EvaluablePublicKeyCredentialCriterion(publicSigningKey) ); try { Credential credential = credentialResolver.resolveSingle(criteriaSet); if (credential instanceof X509Credential) { X509Certificate x509Cert = ((X509Credential)credential).getEntityCertificate(); if (x509Cert.getPublicKey().equals(publicSigningKey)){ return x509Cert; } } } catch (ResolverException e) { throw new SigningKeyExtractionException("Unable to resolve metadata.", e); } throw new SigningKeyExtractionException("Certificate for public signing key not found in metadata."); } @Inject SigningCertFromMetadataExtractor(@Named(VERIFY_METADATA_RESOLVER) MetadataResolver metadataResolver,
@Named("HubEntityId") String hubEntityId); X509Certificate getSigningCertForCurrentSigningKey(PublicKey publicSigningKey); }### Answer:
@Test public void certIsSuccessfullyExtractedFromMetadata() throws ComponentInitializationException, ResolverException { signingCertFromMetadataExtractor = new SigningCertFromMetadataExtractor(metadataResolver, HUB_ENTITY_ID); when(metadataResolver.resolve(any())).thenReturn(List.of(hubEntityDescriptor)); assertThat(signingCertFromMetadataExtractor.getSigningCertForCurrentSigningKey(hubPrimarySigningPublicKey)).isEqualTo(hubPrimarySigningCert); }
@Test public void certIsSuccessfullyExtractedFromMetadataReversed() throws ComponentInitializationException, ResolverException { signingCertFromMetadataExtractor = new SigningCertFromMetadataExtractor(metadataResolver, HUB_ENTITY_ID); when(metadataResolver.resolve(any())).thenReturn(List.of(hubEntityDescriptor)); assertThat(signingCertFromMetadataExtractor.getSigningCertForCurrentSigningKey(hubSecondarySigningPublicKey)).isEqualTo(hubSecondarySigningCert); }
@Test(expected = SigningKeyExtractionException.class) public void certIsNotFoundWhenResolvedMetadataDoesNotContainRelevantCert() throws ComponentInitializationException, ResolverException { signingCertFromMetadataExtractor = new SigningCertFromMetadataExtractor(metadataResolver, HUB_ENTITY_ID); when(metadataResolver.resolve(any())).thenReturn(List.of(hubEntityDescriptor)); signingCertFromMetadataExtractor.getSigningCertForCurrentSigningKey(notHubSigningPublicKey); }
@Test(expected = SigningKeyExtractionException.class) public void certIsNotFoundWhenEmptyMetadataReturned() throws ComponentInitializationException, ResolverException { signingCertFromMetadataExtractor = new SigningCertFromMetadataExtractor(metadataResolver, HUB_ENTITY_ID); when(metadataResolver.resolve(any())).thenReturn(emptyList()); signingCertFromMetadataExtractor.getSigningCertForCurrentSigningKey(notHubSigningPublicKey); }
@Test(expected = SigningKeyExtractionException.class) public void unableToResolveMetadata() throws ComponentInitializationException, ResolverException { signingCertFromMetadataExtractor = new SigningCertFromMetadataExtractor(metadataResolver, HUB_ENTITY_ID); when(metadataResolver.resolve(any())).thenThrow(new ResolverException()); signingCertFromMetadataExtractor.getSigningCertForCurrentSigningKey(hubPrimarySigningCert.getPublicKey()); } |
### Question:
SamlEngineModule extends AbstractModule { @Override protected void configure() { bind(TrustStoreConfiguration.class).to(SamlEngineConfiguration.class); bind(RestfulClientConfiguration.class).to(SamlEngineConfiguration.class); bind(SamlDuplicateRequestValidationConfiguration.class).to(SamlEngineConfiguration.class); bind(SamlAuthnRequestValidityDurationConfiguration.class).to(SamlEngineConfiguration.class); bind(Client.class).toProvider(DefaultClientProvider.class).asEagerSingleton(); bind(EntityToEncryptForLocator.class).to(AssignableEntityToEncryptForLocator.class); bind(AssignableEntityToEncryptForLocator.class).asEagerSingleton(); bind(ReplayCacheStartupTasks.class).asEagerSingleton(); bind(ConfigServiceKeyStore.class).asEagerSingleton(); bind(JsonResponseProcessor.class); bind(RpErrorResponseGeneratorService.class); bind(TransactionsConfigProxy.class); bind(MatchingServiceHealthcheckRequestGeneratorService.class); bind(ExpiredCertificateMetadataFilter.class).toInstance(new ExpiredCertificateMetadataFilter()); bind(new TypeLiteral<LevelLoggerFactory<SamlEngineExceptionMapper>>() {}) .toInstance(new LevelLoggerFactory<>()); bind(OutboundResponseFromHubToResponseTransformerFactory.class); bind(SimpleProfileOutboundResponseFromHubToResponseTransformerProvider.class); bind(SimpleProfileOutboundResponseFromHubToSamlResponseTransformer.class); bind(ResponseToUnsignedStringTransformer.class); bind(ResponseAssertionSigner.class); bind(SimpleProfileTransactionIdaStatusMarshaller.class); bind(EncryptedAssertionUnmarshaller.class).toInstance(hubTransformersFactory.getEncryptedAssertionUnmarshaller()); bind(IdpAuthnResponseTranslatorService.class); bind(InboundResponseFromIdpDataGenerator.class); bind(MatchingServiceRequestGeneratorService.class); bind(HubAttributeQueryRequestBuilder.class); bind(MatchingServiceResponseTranslatorService.class); bind(RpAuthnRequestTranslatorService.class); bind(RpAuthnResponseGeneratorService.class); bind(IdpAuthnRequestGeneratorService.class); bind(IdaAuthnRequestTranslator.class); bind(EidasAuthnRequestTranslator.class); bind(MatchingServiceHealthcheckResponseTranslatorService.class); } @Provides PassthroughAssertionUnmarshaller getPassthroughAssertionUnmarshaller(); @Provides Optional<DestinationValidator> getValidateSamlResponseIssuedByIdpDestination(@Named("ExpectedEidasDestination") Optional<URI> expectedDestination); @Provides @Singleton Optional<EidasValidatorFactory> getEidasValidatorFactory(Optional<EidasMetadataResolverRepository> eidasMetadataResolverRepository, SamlEngineConfiguration configuration); @Provides @Singleton Optional<CountrySingleSignOnServiceHelper> getCountrySingleSignOnServiceHelper(Optional<EidasMetadataResolverRepository> eidasMetadataResolverRepository, SamlEngineConfiguration configuration); @Provides @Singleton Optional<EidasTrustAnchorHealthCheck> getCountryMetadataHealthCheck(
Optional<EidasMetadataResolverRepository> metadataResolverRepository,
Environment environment); static final String COUNTRY_METADATA_HEALTH_CHECK; static final String EIDAS_HUB_ENTITY_ID_NOT_CONFIGURED_ERROR_MESSAGE; static final String VERIFY_METADATA_RESOLVER; static final String FED_METADATA_ENTITY_SIGNATURE_VALIDATOR; static final String VERIFY_METADATA_SIGNATURE_TRUST_ENGINE; }### Answer:
@Test public void configure() { SamlEngineModule sem = new SamlEngineModule(); when(binder.bind(any(Class.class))).thenReturn(builder); when(binder.bind(any(TypeLiteral.class))).thenReturn(builder); when(builder.toProvider(any(Class.class))).thenReturn(scopedBindingBuilder); sem.configure(binder); verify(binder).bind(TrustStoreConfiguration.class); } |
### Question:
SamlProxyExceptionMapper extends AbstractContextExceptionMapper<Exception> { @Override protected Response handleException(Exception exception) { UUID errorId = UUID.randomUUID(); levelLogger.log(ExceptionType.UNKNOWN.getLevel(), exception, errorId); return Response.serverError() .entity(ErrorStatusDto.createAuditedErrorStatus(errorId, ExceptionType.UNKNOWN)) .build(); } @Inject SamlProxyExceptionMapper(
Provider<HttpServletRequest> contextProvider,
LevelLoggerFactory<SamlProxyExceptionMapper> levelLoggerFactory); }### Answer:
@Test public void shouldCreateAuditedErrorResponse() throws Exception { Response response = exceptionMapper.handleException(new RuntimeException()); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); assertThat(responseEntity.isAudited()).isTrue(); }
@Test public void shouldLogExceptionAtErrorLevel() throws Exception { RuntimeException exception = new RuntimeException(); exceptionMapper.handleException(exception); verify(levelLogger).log(eq(Level.ERROR), eq(exception), any(UUID.class)); } |
### Question:
OutboundResponseFromHubToResponseTransformerFactory { public Function<OutboundResponseFromHub, String> get(String authnRequestIssuerEntityId) { if (transactionsConfigProxy.getShouldHubSignResponseMessages(authnRequestIssuerEntityId)) { return transactionsConfigProxy.getShouldHubUseLegacySamlStandard(authnRequestIssuerEntityId) ? outboundLegacyResponseFromHubToStringFunctionSHA256 : outboundSamlProfileResponseFromHubToStringFunctionSHA256; } return simpleProfileOutboundResponseFromHubToResponseTransformerProvider.get(); } @Inject OutboundResponseFromHubToResponseTransformerFactory(SimpleProfileOutboundResponseFromHubToResponseTransformerProvider simpleProfileOutboundResponseFromHubToResponseTransformerProvider,
TransactionsConfigProxy transactionsConfigProxy,
OutboundSamlProfileResponseFromHubToStringFunctionSHA256 outboundSamlProfileResponseFromHubToStringFunctionSHA256,
OutboundLegacyResponseFromHubToStringFunctionSHA256 outboundLegacyResponseFromHubToStringFunctionSHA256,
OutboundAuthnResponseFromCountryContainerToStringFunction outboundAuthnResponseFromCountryContainerToStringFunction); Function<OutboundResponseFromHub, String> get(String authnRequestIssuerEntityId); Function<AuthnResponseFromCountryContainerDto, String> getCountryTransformer(); }### Answer:
@Test public void getShouldReturnOutboundLegacyResponseFromHubToStringFunctionSHA256WhenHubShouldSignResponseMessages() { when(transactionsConfigProxy.getShouldHubSignResponseMessages(ENTITY_ID)).thenReturn(true); when(transactionsConfigProxy.getShouldHubUseLegacySamlStandard(ENTITY_ID)).thenReturn(true); Function<OutboundResponseFromHub, String> transformer = outboundResponseFromHubToResponseTransformerFactory.get(ENTITY_ID); assertThat(transformer).isEqualTo(outboundLegacyResponseFromHubToStringFunctionSHA256); }
@Test public void getShouldReturnOutboundSamlProfileResponseFromHubToStringFunctionSHA256WhenHubShouldSignResponseMessages() { when(transactionsConfigProxy.getShouldHubSignResponseMessages(ENTITY_ID)).thenReturn(true); when(transactionsConfigProxy.getShouldHubUseLegacySamlStandard(ENTITY_ID)).thenReturn(false); Function<OutboundResponseFromHub, String> transformer = outboundResponseFromHubToResponseTransformerFactory.get(ENTITY_ID); assertThat(transformer).isEqualTo(outboundSamlProfileResponseFromHubToStringFunctionSHA256); }
@Test public void getShouldReturnSimpleProfileOutboundResponseFromHubToResponseTransformerProviderWhenHubShouldSignResponseMessages() { when(transactionsConfigProxy.getShouldHubSignResponseMessages(ENTITY_ID)).thenReturn(false); when(simpleProfileOutboundResponseFromHubToResponseTransformerProvider.get()).thenReturn(simpleProfileOutboundResponseFromHubToResponseTransformer); Function<OutboundResponseFromHub, String> transformer = outboundResponseFromHubToResponseTransformerFactory.get(ENTITY_ID); assertThat(transformer).isEqualTo(simpleProfileOutboundResponseFromHubToResponseTransformer); } |
### Question:
OutboundResponseFromHubToResponseTransformerFactory { public Function<AuthnResponseFromCountryContainerDto, String> getCountryTransformer() { return outboundAuthnResponseFromCountryContainerToStringFunction; } @Inject OutboundResponseFromHubToResponseTransformerFactory(SimpleProfileOutboundResponseFromHubToResponseTransformerProvider simpleProfileOutboundResponseFromHubToResponseTransformerProvider,
TransactionsConfigProxy transactionsConfigProxy,
OutboundSamlProfileResponseFromHubToStringFunctionSHA256 outboundSamlProfileResponseFromHubToStringFunctionSHA256,
OutboundLegacyResponseFromHubToStringFunctionSHA256 outboundLegacyResponseFromHubToStringFunctionSHA256,
OutboundAuthnResponseFromCountryContainerToStringFunction outboundAuthnResponseFromCountryContainerToStringFunction); Function<OutboundResponseFromHub, String> get(String authnRequestIssuerEntityId); Function<AuthnResponseFromCountryContainerDto, String> getCountryTransformer(); }### Answer:
@Test public void getCountryTransformerShouldReturnOutboundAuthnResponseFromCountryContainerToStringFunction() { Function<AuthnResponseFromCountryContainerDto, String> transformer = outboundResponseFromHubToResponseTransformerFactory.getCountryTransformer(); assertThat(transformer).isEqualTo(outboundAuthnResponseFromCountryContainerToStringFunction); } |
### Question:
PolicyExceptionMapper implements ExceptionMapper<TException> { @Override public final Response toResponse(TException exception) { if (exception instanceof NotFoundException) { return Response.status(Response.Status.NOT_FOUND).build(); } else if (noSessionIdInQueryStringOrPathParam() && inARequestWhereWeExpectContext()) { LOG.error(MessageFormat.format("No Session Id found for request to: {0}", httpServletRequest.getRequestURI()), exception); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return handleException(exception); } PolicyExceptionMapper(); @Context void setUriInfo(UriInfo uriInfo); @Context void setHttpServletRequest(HttpServletRequest httpServletRequest); @Override final Response toResponse(TException exception); }### Answer:
@Test public void shouldReturnInternalServerErrorWhenThereIsNoSessionIdAndTheRequestUriIsNotAKnownNoContextPath() { when(servletRequest.getParameter(Urls.SharedUrls.SESSION_ID_PARAM)).thenReturn(""); when(servletRequest.getParameter(Urls.SharedUrls.RELAY_STATE_PARAM)).thenReturn(""); when(uriInfo.getPathParameters()).thenReturn(new StringKeyIgnoreCaseMultivaluedMap<>()); String unknownUri = UUID.randomUUID().toString(); when(servletRequest.getRequestURI()).thenReturn(unknownUri); Response response = mapper.toResponse(new RuntimeException("We don't expect to see this message")); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); }
@Test public void shouldReturnResponseStatusOfNotFoundWhenANotFoundExceptionIsThrown() { Response response = mapper.toResponse(new NotFoundException()); assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); } |
### Question:
AuthnRequestFromTransactionHandler { public SessionId handleRequestFromTransaction(SamlResponseWithAuthnRequestInformationDto samlResponse, Optional<String> relayState, String ipAddress, URI assertionConsumerServiceUri, boolean transactionSupportsEidas) { Duration sessionLength = policyConfiguration.getSessionLength(); DateTime sessionExpiryTimestamp = DateTime.now().plus(sessionLength); SessionId sessionId = SessionId.createNewSessionId(); SessionStartedState sessionStartedState = new SessionStartedState( samlResponse.getId(), relayState.orElse(null), samlResponse.getIssuer(), assertionConsumerServiceUri, samlResponse.getForceAuthentication().orElse(null), sessionExpiryTimestamp, sessionId, transactionSupportsEidas); final List<LevelOfAssurance> transactionLevelsOfAssurance = transactionsConfigProxy.getLevelsOfAssurance(samlResponse.getIssuer()); hubEventLogger.logSessionStartedEvent( samlResponse, ipAddress, sessionExpiryTimestamp, sessionId, Collections.min(transactionLevelsOfAssurance), Collections.max(transactionLevelsOfAssurance), transactionLevelsOfAssurance.get(0)); return sessionRepository.createSession(sessionStartedState); } @Inject AuthnRequestFromTransactionHandler(
SessionRepository sessionRepository,
HubEventLogger hubEventLogger,
PolicyConfiguration policyConfiguration,
TransactionsConfigProxy transactionsConfigProxy,
IdGenerator idGenerator); SessionId handleRequestFromTransaction(SamlResponseWithAuthnRequestInformationDto samlResponse, Optional<String> relayState, String ipAddress, URI assertionConsumerServiceUri, boolean transactionSupportsEidas); void tryAnotherIdp(final SessionId sessionId); void restartJourney(final SessionId sessionId); void selectIdpForGivenSessionId(SessionId sessionId, IdpSelected idpSelected); AuthnRequestFromHub getIdaAuthnRequestFromHub(SessionId sessionId); AuthnRequestSignInProcess getSignInProcessDto(SessionId sessionIdParameter); String getRequestIssuerId(SessionId sessionId); ResponseFromHub getResponseFromHub(SessionId sessionId); ResponseFromHub getErrorResponseFromHub(SessionId sessionId); AuthnResponseFromCountryContainerDto getAuthnResponseFromCountryContainerDto(SessionId sessionId); boolean isResponseFromCountryWithUnsignedAssertions(SessionId sessionId); }### Answer:
@Test public void testHandleRequestFromTransaction_logsToEventSink() { final SamlResponseWithAuthnRequestInformationDto samlResponseWithAuthnRequestInformationDto = SamlResponseWithAuthnRequestInformationDtoBuilder.aSamlResponseWithAuthnRequestInformationDto().build(); final Optional<String> relayState = Optional.of(RELAY_STATE); when(policyConfiguration.getSessionLength()).thenReturn(Duration.standardHours(1)); when(transactionsConfigProxy.getLevelsOfAssurance(samlResponseWithAuthnRequestInformationDto.getIssuer())).thenReturn(asList(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_1)); authnRequestFromTransactionHandler.handleRequestFromTransaction(samlResponseWithAuthnRequestInformationDto, relayState, PRINCIPAL_IP_ADDRESS, ASSERTION_CONSUMER_SERVICE_URI, false); verify(hubEventLogger, times(1)).logSessionStartedEvent( any(), anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()); } |
### Question:
AuthnRequestFromTransactionHandler { public void selectIdpForGivenSessionId(SessionId sessionId, IdpSelected idpSelected) { IdpSelectingStateController stateController = (IdpSelectingStateController) sessionRepository.getStateController(sessionId, IdpSelectingState.class); stateController.handleIdpSelected(idpSelected.getSelectedIdpEntityId(), idpSelected.getPrincipalIpAddress(), idpSelected.isRegistration(), idpSelected.getRequestedLoa(), idpSelected.getAnalyticsSessionId(), idpSelected.getJourneyType(), idpSelected.getAbTestVariant()); } @Inject AuthnRequestFromTransactionHandler(
SessionRepository sessionRepository,
HubEventLogger hubEventLogger,
PolicyConfiguration policyConfiguration,
TransactionsConfigProxy transactionsConfigProxy,
IdGenerator idGenerator); SessionId handleRequestFromTransaction(SamlResponseWithAuthnRequestInformationDto samlResponse, Optional<String> relayState, String ipAddress, URI assertionConsumerServiceUri, boolean transactionSupportsEidas); void tryAnotherIdp(final SessionId sessionId); void restartJourney(final SessionId sessionId); void selectIdpForGivenSessionId(SessionId sessionId, IdpSelected idpSelected); AuthnRequestFromHub getIdaAuthnRequestFromHub(SessionId sessionId); AuthnRequestSignInProcess getSignInProcessDto(SessionId sessionIdParameter); String getRequestIssuerId(SessionId sessionId); ResponseFromHub getResponseFromHub(SessionId sessionId); ResponseFromHub getErrorResponseFromHub(SessionId sessionId); AuthnResponseFromCountryContainerDto getAuthnResponseFromCountryContainerDto(SessionId sessionId); boolean isResponseFromCountryWithUnsignedAssertions(SessionId sessionId); }### Answer:
@Test public void stateControllerInvokedFromSessionRepositoryForselectedIdp() { IdpSelected idpSelected = new IdpSelected(IDP_ENTITY_ID, PRINCIPAL_IP_ADDRESS, REGISTERING, REQUESTED_LOA, ANALYTICS_SESSION_ID, JOURNEY_TYPE, ""); IdpSelectingStateControllerSpy idpSelectingStateController = new IdpSelectingStateControllerSpy(); when(sessionRepository.getStateController(SESSION_ID, IdpSelectingState.class)).thenReturn((idpSelectingStateController)); authnRequestFromTransactionHandler.selectIdpForGivenSessionId(SESSION_ID, idpSelected); assertThat(idpSelectingStateController.idpEntityId()).isEqualTo(IDP_ENTITY_ID); assertThat(idpSelectingStateController.principalIpAddress()).isEqualTo(PRINCIPAL_IP_ADDRESS); assertThat(idpSelectingStateController.registering()).isEqualTo(REGISTERING); assertThat(idpSelectingStateController.getRequestedLoa()).isEqualTo(REQUESTED_LOA); } |
### Question:
AuthnRequestFromTransactionHandler { public void restartJourney(final SessionId sessionId) { final RestartJourneyStateController stateController = (RestartJourneyStateController) sessionRepository.getStateController(sessionId, RestartJourneyState.class); stateController.transitionToSessionStartedState(); } @Inject AuthnRequestFromTransactionHandler(
SessionRepository sessionRepository,
HubEventLogger hubEventLogger,
PolicyConfiguration policyConfiguration,
TransactionsConfigProxy transactionsConfigProxy,
IdGenerator idGenerator); SessionId handleRequestFromTransaction(SamlResponseWithAuthnRequestInformationDto samlResponse, Optional<String> relayState, String ipAddress, URI assertionConsumerServiceUri, boolean transactionSupportsEidas); void tryAnotherIdp(final SessionId sessionId); void restartJourney(final SessionId sessionId); void selectIdpForGivenSessionId(SessionId sessionId, IdpSelected idpSelected); AuthnRequestFromHub getIdaAuthnRequestFromHub(SessionId sessionId); AuthnRequestSignInProcess getSignInProcessDto(SessionId sessionIdParameter); String getRequestIssuerId(SessionId sessionId); ResponseFromHub getResponseFromHub(SessionId sessionId); ResponseFromHub getErrorResponseFromHub(SessionId sessionId); AuthnResponseFromCountryContainerDto getAuthnResponseFromCountryContainerDto(SessionId sessionId); boolean isResponseFromCountryWithUnsignedAssertions(SessionId sessionId); }### Answer:
@Test public void restartsJourney() { when(sessionRepository.getStateController(SESSION_ID, RestartJourneyState.class)).thenReturn(restartJourneyStateController); authnRequestFromTransactionHandler.restartJourney(SESSION_ID); verify(restartJourneyStateController).transitionToSessionStartedState(); } |
### Question:
AuthnRequestFromTransactionHandler { public AuthnResponseFromCountryContainerDto getAuthnResponseFromCountryContainerDto(SessionId sessionId) { NonMatchingJourneySuccessStateController stateController = (NonMatchingJourneySuccessStateController) sessionRepository.getStateController(sessionId, ResponsePreparedState.class); NonMatchingJourneySuccessState state = stateController.getState(); return new AuthnResponseFromCountryContainerDto( state.getCountrySignedResponseContainer().get(), state.getAssertionConsumerServiceUri(), state.getRelayState(), state.getRequestId(), state.getRequestIssuerEntityId(), idGenerator.getId() ); } @Inject AuthnRequestFromTransactionHandler(
SessionRepository sessionRepository,
HubEventLogger hubEventLogger,
PolicyConfiguration policyConfiguration,
TransactionsConfigProxy transactionsConfigProxy,
IdGenerator idGenerator); SessionId handleRequestFromTransaction(SamlResponseWithAuthnRequestInformationDto samlResponse, Optional<String> relayState, String ipAddress, URI assertionConsumerServiceUri, boolean transactionSupportsEidas); void tryAnotherIdp(final SessionId sessionId); void restartJourney(final SessionId sessionId); void selectIdpForGivenSessionId(SessionId sessionId, IdpSelected idpSelected); AuthnRequestFromHub getIdaAuthnRequestFromHub(SessionId sessionId); AuthnRequestSignInProcess getSignInProcessDto(SessionId sessionIdParameter); String getRequestIssuerId(SessionId sessionId); ResponseFromHub getResponseFromHub(SessionId sessionId); ResponseFromHub getErrorResponseFromHub(SessionId sessionId); AuthnResponseFromCountryContainerDto getAuthnResponseFromCountryContainerDto(SessionId sessionId); boolean isResponseFromCountryWithUnsignedAssertions(SessionId sessionId); }### Answer:
@Test public void getAuthnResponseFromCountryContainerDtoReturnsAnAuthnResponseFromCountryContainerDto() throws URISyntaxException { NonMatchingJourneySuccessStateController stateContoller = mock(NonMatchingJourneySuccessStateController.class); when(sessionRepository.getStateController(SESSION_ID, ResponsePreparedState.class)).thenReturn(stateContoller); when(stateContoller.getState()).thenReturn(setupNonMatchingJourneySuccessState(SESSION_ID, true)); when(idGenerator.getId()).thenReturn(GENERATED_ID); AuthnResponseFromCountryContainerDto responseDto = authnRequestFromTransactionHandler.getAuthnResponseFromCountryContainerDto(SESSION_ID); assertThat(responseDto.getSamlResponse()).isEqualTo(SAML_RESPONSE); assertThat(responseDto.getEncryptedKeys()).isEqualTo(asList(ENCRYPTED_KEY)); assertThat(responseDto.getPostEndpoint()).isEqualTo(ASSERTION_CONSUMER_SERVICE_URI); assertThat(responseDto.getRelayState().get()).isEqualTo(RELAY_STATE); assertThat(responseDto.getInResponseTo()).isEqualTo(REQUEST_ID); assertThat(responseDto.getResponseId()).isEqualTo(GENERATED_ID); } |
### Question:
AuthnRequestFromTransactionHandler { public boolean isResponseFromCountryWithUnsignedAssertions(SessionId sessionId) { StateController stateController = sessionRepository.getStateController(sessionId, ResponsePreparedState.class); if (stateController instanceof NonMatchingJourneySuccessStateController) { NonMatchingJourneySuccessState state = ((NonMatchingJourneySuccessStateController) stateController).getState(); return state.getCountrySignedResponseContainer().isPresent(); } return false; } @Inject AuthnRequestFromTransactionHandler(
SessionRepository sessionRepository,
HubEventLogger hubEventLogger,
PolicyConfiguration policyConfiguration,
TransactionsConfigProxy transactionsConfigProxy,
IdGenerator idGenerator); SessionId handleRequestFromTransaction(SamlResponseWithAuthnRequestInformationDto samlResponse, Optional<String> relayState, String ipAddress, URI assertionConsumerServiceUri, boolean transactionSupportsEidas); void tryAnotherIdp(final SessionId sessionId); void restartJourney(final SessionId sessionId); void selectIdpForGivenSessionId(SessionId sessionId, IdpSelected idpSelected); AuthnRequestFromHub getIdaAuthnRequestFromHub(SessionId sessionId); AuthnRequestSignInProcess getSignInProcessDto(SessionId sessionIdParameter); String getRequestIssuerId(SessionId sessionId); ResponseFromHub getResponseFromHub(SessionId sessionId); ResponseFromHub getErrorResponseFromHub(SessionId sessionId); AuthnResponseFromCountryContainerDto getAuthnResponseFromCountryContainerDto(SessionId sessionId); boolean isResponseFromCountryWithUnsignedAssertions(SessionId sessionId); }### Answer:
@Test public void isResponseFromCountryWithUnsignedAssertionsReturnsTrueIfCountrySignedResponseWithKeysIsPresent() { NonMatchingJourneySuccessStateController stateContoller = mock(NonMatchingJourneySuccessStateController.class); when(sessionRepository.getStateController(SESSION_ID, ResponsePreparedState.class)).thenReturn(stateContoller); when(stateContoller.getState()).thenReturn(setupNonMatchingJourneySuccessState(SESSION_ID, true)); assertThat(authnRequestFromTransactionHandler.isResponseFromCountryWithUnsignedAssertions(SESSION_ID)).isTrue(); }
@Test public void isResponseFromCountryWithUnsignedAssertionsReturnsFalseIfCountrySignedResponseWithKeysIsNotPresent() { NonMatchingJourneySuccessStateController stateContoller = mock(NonMatchingJourneySuccessStateController.class); when(sessionRepository.getStateController(SESSION_ID, ResponsePreparedState.class)).thenReturn(stateContoller); when(stateContoller.getState()).thenReturn(setupNonMatchingJourneySuccessState(SESSION_ID, false)); assertThat(authnRequestFromTransactionHandler.isResponseFromCountryWithUnsignedAssertions(SESSION_ID)).isFalse(); }
@Test public void isResponseFromCountryWithUnsignedAssertionsReturnsFalseIfStateControllerIsNotNonMatchingJourneySuccess() { EidasSuccessfulMatchStateController stateContoller = mock(EidasSuccessfulMatchStateController.class); when(sessionRepository.getStateController(SESSION_ID, ResponsePreparedState.class)).thenReturn(stateContoller); assertThat(authnRequestFromTransactionHandler.isResponseFromCountryWithUnsignedAssertions(SESSION_ID)).isFalse(); } |
### Question:
EidasConnectorMetrics { public static void increment(String entityId, Direction direction, Status status) { try { String country = getCountryCode(Objects.requireNonNull(entityId)); CONNECTOR_COUNTER.labels( country.toLowerCase(), Objects.requireNonNull(direction.name()), Objects.requireNonNull(status.name())) .inc(); } catch (IllegalArgumentException | NullPointerException e) { LOG.warn("Could not set counter for entityId '{}', direction '{}', status '{}'", entityId, direction, status, e); } } static void increment(String entityId, Direction direction, Status status); }### Answer:
@Test public void testIncrementingCounterWithParameters() throws Exception { Counter counter = mock(Counter.class); Counter.Child counterChild = mock(Counter.Child.class); setFinalStatic(EidasConnectorMetrics.class.getDeclaredField("CONNECTOR_COUNTER"), counter); when(counter.labels(expectedCountryCode, direction != null ? direction.name() : null, status != null ? status.name() : null)).thenReturn(counterChild); EidasConnectorMetrics.increment(entityId, direction, status); if (incrementsCounter) { verify(counterChild).inc(); } else { verifyNoInteractions(counter, counterChild); } } |
### Question:
TransactionsConfigProxy { @Timed public boolean isUsingMatching( String entityId ) { return getConfigItem( entityId, Urls.ConfigUrls.MATCHING_ENABLED_FOR_TRANSACTION_RESOURCE, boolean.class, emptyMap()); } @Inject TransactionsConfigProxy(
JsonClient jsonClient,
@Config URI configUri); @Timed ResourceLocation getAssertionConsumerServiceUri(String entityId, Optional<Integer> assertionConsumerServiceIndex); @Timed MatchingProcess getMatchingProcess(String entityId); @Timed boolean getEidasSupportedForEntity(String entityId); @Timed boolean isUsingMatching( String entityId ); @Timed List<LevelOfAssurance> getLevelsOfAssurance(String entityId); @Timed String getMatchingServiceEntityId(String entityId); @Timed List<UserAccountCreationAttribute> getUserAccountCreationAttributes(String entityId); @Timed List<EidasCountryDto> getEidasSupportedCountries(); @Timed List<String> getEidasSupportedCountriesForRP(String relyingPartyEntityId); }### Answer:
@Test public void whenUrlForIsUsingMatchingIsValidReturnTrue() { String entityId = ENTITY_ID; configProxy = new TransactionsConfigProxy( client, CONFIG_BASE_URI ); URI isUsingMatchingUri = UriBuilder .fromUri(CONFIG_BASE_URI) .path(Urls.ConfigUrls.MATCHING_ENABLED_FOR_TRANSACTION_RESOURCE) .buildFromEncoded(StringEncoding.urlEncode(entityId) .replace("+", "%20")); when(client.get(eq(isUsingMatchingUri), eq(boolean.class))).thenReturn(true); assertThat(configProxy.isUsingMatching(entityId)).isTrue(); }
@Test public void whenUrlForIsUsingMatchingIsValidReturnFalse() { String entityId = ENTITY_ID; configProxy = new TransactionsConfigProxy( client, CONFIG_BASE_URI ); URI isUsingMatchingUri = UriBuilder .fromUri(CONFIG_BASE_URI) .path(Urls.ConfigUrls.MATCHING_ENABLED_FOR_TRANSACTION_RESOURCE) .buildFromEncoded(StringEncoding.urlEncode(entityId) .replace("+", "%20")); when(client.get(eq(isUsingMatchingUri), eq(boolean.class))).thenReturn(false); assertThat(configProxy.isUsingMatching(entityId)).isFalse(); }
@Test(expected = RuntimeException.class) public void shouldPropagateExceptionWhenIsUsingMatchingResultsInARuntimeException() { configProxy = new TransactionsConfigProxy( client, CONFIG_BASE_URI ); when(client.get(any(), eq(boolean.class))).thenThrow(new RuntimeException()); configProxy.isUsingMatching(ENTITY_ID); } |
### Question:
HubAsIdpMetadataHandler { public HubIdentityProviderMetadataDto getMetadataAsAnIdentityProvider() { URI hubFrontend = samlProxyConfiguration.getFrontendExternalUri(); SamlEndpointDto binding = new SamlEndpointDto(SamlEndpointDto.Binding.POST, URI.create(hubFrontend + SAML2_SSO_REQUEST_ENDPOINT)); Iterable<EntityDescriptor> entityDescriptors; try { CriteriaSet criteria = new CriteriaSet(new EntitiesDescriptorNameCriterion(hubFederationId)); entityDescriptors = metadataResolver.resolve(criteria); LOG.info("Retrieved metadata from " + samlProxyConfiguration.getMetadataConfiguration().getUri()); } catch (ResolverException e) { throw ApplicationException.createUnauditedException(ExceptionType.METADATA_PROVIDER_EXCEPTION, e.getMessage(), e); } final Iterable<EntityDescriptor> idpEntityDescriptors = StreamSupport .stream(entityDescriptors.spliterator(), false) .filter(input -> input.getIDPSSODescriptor(SAMLConstants.SAML20P_NS) != null) .collect(Collectors.toList()); final Iterable<EntityDescriptor> hubEntityDescriptors = StreamSupport .stream(entityDescriptors.spliterator(), false) .filter(input -> input.getEntityID().equals(hubEntityId)) .collect(Collectors.toList()); final Iterable<List<Certificate>> idpSigningCertificates = StreamSupport .stream(idpEntityDescriptors.spliterator(), false) .map(this::getIDPSigningCertificates) .collect(Collectors.toList()); final Iterable<Certificate> hubEncryptionCertificate = StreamSupport .stream(hubEntityDescriptors.spliterator(), false) .map(this::getHubEncryptionCertificate) .collect(Collectors.toList()); final Iterable<List<Certificate>> hubSigningCertificates = StreamSupport .stream(hubEntityDescriptors.spliterator(), false) .map(this::getHubSigningCertificates) .collect(Collectors.toList()); return new HubIdentityProviderMetadataDto( singletonList(binding), hubEntityId, organisationDto, Collections.emptySet(), ImmutableList.copyOf(Iterables.concat(idpSigningCertificates)), DateTime.now().plus(samlProxyConfiguration.getMetadataValidDuration().toMilliseconds()), ImmutableList.copyOf(Iterables.concat(hubSigningCertificates)), hubEncryptionCertificate.iterator().next() ); } @Inject HubAsIdpMetadataHandler(
MetadataResolver metadataResolver,
SamlProxyConfiguration samlProxyConfiguration,
@Named("HubEntityId") String hubEntityId,
@Named("HubFederationId") String hubFederationId); HubIdentityProviderMetadataDto getMetadataAsAnIdentityProvider(); }### Answer:
@Test public void shouldReturnSingleHubEncryptionCert() { HubIdentityProviderMetadataDto metadataAsAnIdentityProvider = handler.getMetadataAsAnIdentityProvider(); final List<Certificate> encryptionCertificates = metadataAsAnIdentityProvider.getEncryptionCertificates(); assertThat(encryptionCertificates).hasSize(1); final Optional<Certificate> hubEncryptionCertificate = encryptionCertificates.stream().filter(getPredicateByIssuerId(TestEntityIds.HUB_ENTITY_ID)).findFirst(); assertThat(hubEncryptionCertificate.isPresent()).isTrue(); assertThat(hubEncryptionCertificate.get().getKeyUse()).isEqualTo(Certificate.KeyUse.Encryption); }
@Test public void shouldReturnHubSigningCerts() { HubIdentityProviderMetadataDto metadataAsAnIdentityProvider = handler.getMetadataAsAnIdentityProvider(); final List<Certificate> signingCertificates = metadataAsAnIdentityProvider.getSigningCertificates(); assertThat(signingCertificates).hasSize(2); assertThat(signingCertificates.get(0).getKeyUse()).isEqualTo(Certificate.KeyUse.Signing); assertThat(signingCertificates.get(1).getKeyUse()).isEqualTo(Certificate.KeyUse.Signing); } |
### Question:
AttributeQueryService { public void sendAttributeQueryRequest( final SessionId sessionId, final AbstractAttributeQueryRequestDto attributeQueryRequestDto) { AttributeQueryContainerDto attributeQueryContainerDto = attributeQueryRequestDto.sendToSamlEngine(samlEngineProxy); generateAndSendMatchingServiceRequest(sessionId, attributeQueryRequestDto.isOnboarding(), attributeQueryContainerDto); } @Inject AttributeQueryService(SamlEngineProxy samlEngineProxy, SamlSoapProxyProxy samlSoapProxyProxy); void sendAttributeQueryRequest(
final SessionId sessionId,
final AbstractAttributeQueryRequestDto attributeQueryRequestDto); }### Answer:
@Test public void shouldGenerateAttributeQueryAndSendRequestToMatchingService() { AttributeQueryRequestDto attributeQueryRequestDto = AttributeQueryRequestBuilder.anAttributeQueryRequest().build(); AttributeQueryContainerDto build = anAttributeQueryContainerDto().build(); when(samlEngineProxy.generateAttributeQuery(attributeQueryRequestDto)).thenReturn(build); service.sendAttributeQueryRequest(sessionId, attributeQueryRequestDto); verify(samlEngineProxy).generateAttributeQuery(attributeQueryRequestDto); verify(samlSoapProxyProxy).sendHubMatchingServiceRequest(eq(sessionId), any()); }
@Test(expected = ApplicationException.class) public void shouldPropagateExceptionThrownBySamlEngineAndNotSendAttributeQuery() { AttributeQueryRequestDto attributeQueryRequestDto = AttributeQueryRequestBuilder.anAttributeQueryRequest().build(); when(samlEngineProxy.generateAttributeQuery(attributeQueryRequestDto)) .thenThrow(ApplicationException.createAuditedException(INVALID_SAML, UUID.randomUUID())); service.sendAttributeQueryRequest(sessionId, attributeQueryRequestDto); verify(samlEngineProxy, times(1)).generateAttributeQuery(attributeQueryRequestDto); verify(samlSoapProxyProxy, times(0)).sendHubMatchingServiceRequest(eq(sessionId), any()); }
@Test public void shouldGenerateEidasAttributeQueryAndSendRequestToMatchingService() { final EidasAttributeQueryRequestDto eidasAttributeQueryRequestDto = anEidasAttributeQueryRequestDto().build(); final AttributeQueryContainerDto attributeQueryContainerDto = anAttributeQueryContainerDto().build(); final AttributeQueryRequest attributeQueryRequest = new AttributeQueryRequest( attributeQueryContainerDto.getId(), attributeQueryContainerDto.getIssuer(), attributeQueryContainerDto.getSamlRequest(), attributeQueryContainerDto.getMatchingServiceUri(), attributeQueryContainerDto.getAttributeQueryClientTimeOut(), eidasAttributeQueryRequestDto.isOnboarding() ); when(samlEngineProxy.generateEidasAttributeQuery(eidasAttributeQueryRequestDto)).thenReturn(attributeQueryContainerDto); service.sendAttributeQueryRequest(sessionId, eidasAttributeQueryRequestDto); verify(samlEngineProxy).generateEidasAttributeQuery(eidasAttributeQueryRequestDto); verify(samlSoapProxyProxy).sendHubMatchingServiceRequest(sessionId, attributeQueryRequest); } |
### Question:
CountriesService { public List<EidasCountryDto> getCountries(SessionId sessionId) { ensureTransactionSupportsEidas(sessionId); List<EidasCountryDto> eidasSupportedCountries = configProxy.getEidasSupportedCountries(); String relyingPartyId = sessionRepository.getRequestIssuerEntityId(sessionId); List<String> rpSpecificCountries = configProxy.getEidasSupportedCountriesForRP(relyingPartyId); return eidasSupportedCountries.stream() .filter(EidasCountryDto::getEnabled) .filter(country -> rpSpecificCountries.isEmpty() || rpSpecificCountries.contains(country.getEntityId())) .collect(Collectors.toList()); } @Inject CountriesService(SessionRepository sessionRepository, TransactionsConfigProxy configProxy); List<EidasCountryDto> getCountries(SessionId sessionId); void setSelectedCountry(SessionId sessionId, String countryCode); }### Answer:
@Test(expected = EidasNotSupportedException.class) public void shouldReturnErrorWhenGettingCountriesWithTxnNotSupportingEidas() { when(sessionRepository.getTransactionSupportsEidas(sessionId)).thenReturn(false); service.getCountries(sessionId); }
@Test public void shouldReturnEnabledSystemWideCountriesWhenRpHasNoExplicitlyEnabledCountries() { setSystemWideCountries(asList(COUNTRY_1, COUNTRY_2, DISABLED_COUNTRY)); List<EidasCountryDto> countries = service.getCountries(sessionId); assertThat(countries).isEqualTo(asList(COUNTRY_1, COUNTRY_2)); }
@Test public void shouldReturnIntersectionOfEnabledSystemWideCountriesAndRPConfiguredCountries() { setSystemWideCountries(asList(COUNTRY_1, COUNTRY_2, DISABLED_COUNTRY)); when(sessionRepository.getRequestIssuerEntityId(sessionId)).thenReturn(RELYING_PARTY_ID); when(configProxy.getEidasSupportedCountriesForRP(RELYING_PARTY_ID)).thenReturn(singletonList(COUNTRY_2.getEntityId())); assertThat(service.getCountries(sessionId)).isEqualTo(singletonList(COUNTRY_2)); } |
### Question:
CountriesService { public void setSelectedCountry(SessionId sessionId, String countryCode) { ensureTransactionSupportsEidas(sessionId); List<EidasCountryDto> supportedCountries = getCountries(sessionId); EidasCountryDto selectedCountry = supportedCountries.stream() .filter(country -> country.getSimpleId().equals(countryCode)) .findFirst() .orElseThrow(() -> new EidasCountryNotSupportedException(sessionId, countryCode)); EidasCountrySelectingStateController eidasCountrySelectingStateController = (EidasCountrySelectingStateController) sessionRepository.getStateController(sessionId, EidasCountrySelectingState.class); eidasCountrySelectingStateController.selectCountry(selectedCountry.getEntityId()); } @Inject CountriesService(SessionRepository sessionRepository, TransactionsConfigProxy configProxy); List<EidasCountryDto> getCountries(SessionId sessionId); void setSelectedCountry(SessionId sessionId, String countryCode); }### Answer:
@Test public void shouldSetSelectedCountry() { EidasCountrySelectedStateController mockEidasCountrySelectedStateController = mock(EidasCountrySelectedStateController.class); when(sessionRepository.getStateController(sessionId, EidasCountrySelectingState.class)).thenReturn(mockEidasCountrySelectedStateController); setSystemWideCountries(singletonList(COUNTRY_1)); service.setSelectedCountry(sessionId, COUNTRY_1.getSimpleId()); verify(mockEidasCountrySelectedStateController).selectCountry(COUNTRY_1.getEntityId()); }
@Test(expected = EidasCountryNotSupportedException.class) public void shouldReturnErrorWhenAnInvalidCountryIsSelected() { setSystemWideCountries(singletonList(COUNTRY_1)); service.setSelectedCountry(sessionId, "not-a-valid-country-code"); }
@Test(expected = EidasNotSupportedException.class) public void shouldReturnErrorWhenACountryIsSelectedWithTxnNotSupportingEidas() { when(sessionRepository.getTransactionSupportsEidas(sessionId)).thenReturn(false); service.setSelectedCountry(sessionId, "NL"); } |
### Question:
ProtectiveMonitoringLogFormatter { public String formatAuthnResponse(Response samlResponse, Direction direction, SignatureStatus signatureStatus) { Issuer issuer = samlResponse.getIssuer(); String issuerString = issuer != null ? issuer.getValue() : ""; Status status = samlResponse.getStatus(); StatusCode subStatusCode = status.getStatusCode().getStatusCode(); String subStatus = subStatusCode != null ? subStatusCode.getValue() : ""; return String.format(AUTHN_RESPONSE, samlResponse.getID(), samlResponse.getInResponseTo(), direction, samlResponse.getDestination(), issuerString, signatureStatus.valid(), status.getStatusCode().getValue(), subStatus, getStatusDetailValues(status)); } String formatAuthnRequest(AuthnRequest authnRequest, Direction direction, SignatureStatus signatureStatus); String formatAuthnResponse(Response samlResponse, Direction direction, SignatureStatus signatureStatus); }### Answer:
@Test public void shouldFormatAuthnCancelResponse() throws IOException, URISyntaxException { String cancelXml = readXmlFile("status-cancel.xml"); Response cancelResponse = stringtoOpenSamlObjectTransformer.apply(cancelXml); String logString = new ProtectiveMonitoringLogFormatter().formatAuthnResponse(cancelResponse, Direction.INBOUND, SignatureStatus.VALID_SIGNATURE); String expectedLogMessage = "Protective Monitoring – Authn Response Event – " + "{responseId: _ccb1eabc4827928c9cbb3db34fdbe9df186dfcb8, " + "inResponseTo: _7081cbd6-a811-440a-949a-12a9521ed7cc, " + "direction: INBOUND, " + "destination: https: "issuerId: http: "validSignature: true, " + "status: urn:oasis:names:tc:SAML:2.0:status:Responder, " + "subStatus: urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext, " + "statusDetails: [authn-cancel]}"; assertThat(logString).isEqualTo(expectedLogMessage); }
@Test public void shouldFormatAuthnSuccessResponse() throws MarshallingException, SignatureException { Response response = aResponse().build(); String logString = new ProtectiveMonitoringLogFormatter().formatAuthnResponse(response, Direction.INBOUND, SignatureStatus.VALID_SIGNATURE); String expectedLogMessage = "Protective Monitoring – Authn Response Event – " + "{responseId: " + DEFAULT_RESPONSE_ID + ", " + "inResponseTo: " + DEFAULT_REQUEST_ID + ", " + "direction: INBOUND, " + "destination: http: "issuerId: a-test-entity, " + "validSignature: true, " + "status: urn:oasis:names:tc:SAML:2.0:status:Success, " + "subStatus: , " + "statusDetails: []}"; assertThat(logString).isEqualTo(expectedLogMessage); }
@Test public void shouldFormatResponseWithNoIssuer() throws MarshallingException, SignatureException { Response response = aResponse().withIssuer(null).build(); String logString = new ProtectiveMonitoringLogFormatter().formatAuthnResponse(response, Direction.INBOUND, SignatureStatus.VALID_SIGNATURE); assertThat(logString).contains("issuerId: ,"); } |
### Question:
Cycle3Service { public Cycle3AttributeRequestData getCycle3AttributeRequestData(SessionId sessionId) { AbstractAwaitingCycle3DataStateController controller = (AbstractAwaitingCycle3DataStateController) sessionRepository.getStateController(sessionId, AbstractAwaitingCycle3DataState.class); return controller.getCycle3AttributeRequestData(); } @Inject Cycle3Service(SessionRepository sessionRepository, AttributeQueryService attributeQueryService); void sendCycle3MatchingRequest(SessionId sessionId, Cycle3UserInput cycle3UserInput); void cancelCycle3DataInput(SessionId sessionId); Cycle3AttributeRequestData getCycle3AttributeRequestData(SessionId sessionId); }### Answer:
@Test public void shouldReturnCycle3AttributeRequestDataAfterReceivingCycle3AttributeRequestDataForVerifyFlow() { when(awaitingCycle3DataStateController.getCycle3AttributeRequestData()).thenReturn(ATTRIBUTE_REQUEST_DATA); Cycle3AttributeRequestData result = service.getCycle3AttributeRequestData(sessionId); assertThat(result).isEqualTo(ATTRIBUTE_REQUEST_DATA); }
@Test public void shouldReturnCycle3AttributeRequestDataAfterReceivingCycle3AttributeRequestDataForEidasFlow() { SessionId eidasSessionId = SessionIdBuilder.aSessionId().build(); when(sessionRepository.getStateController(eidasSessionId, AbstractAwaitingCycle3DataState.class)).thenReturn(eidasAwaitingCycle3DataStateController); when(eidasAwaitingCycle3DataStateController.getCycle3AttributeRequestData()).thenReturn(ATTRIBUTE_REQUEST_DATA); Cycle3AttributeRequestData result = service.getCycle3AttributeRequestData(eidasSessionId); assertThat(result).isEqualTo(ATTRIBUTE_REQUEST_DATA); } |
### Question:
Cycle3Service { public void cancelCycle3DataInput(SessionId sessionId) { AbstractAwaitingCycle3DataStateController controller = (AbstractAwaitingCycle3DataStateController) sessionRepository.getStateController(sessionId, AbstractAwaitingCycle3DataState.class); controller.handleCancellation(); } @Inject Cycle3Service(SessionRepository sessionRepository, AttributeQueryService attributeQueryService); void sendCycle3MatchingRequest(SessionId sessionId, Cycle3UserInput cycle3UserInput); void cancelCycle3DataInput(SessionId sessionId); Cycle3AttributeRequestData getCycle3AttributeRequestData(SessionId sessionId); }### Answer:
@Test public void shouldProcessCancellationAfterReceivingCancelCycle3DataInputForEidasFlow() { SessionId eidasSessionId = SessionIdBuilder.aSessionId().build(); when(sessionRepository.getStateController(eidasSessionId, AbstractAwaitingCycle3DataState.class)).thenReturn(eidasAwaitingCycle3DataStateController); doNothing().when(eidasAwaitingCycle3DataStateController).handleCancellation(); service.cancelCycle3DataInput(eidasSessionId); verify(eidasAwaitingCycle3DataStateController).handleCancellation(); } |
### Question:
SessionService { public SessionId getSessionIfItExists(SessionId sessionId) { if (sessionRepository.sessionExists(sessionId)) { return sessionId; } throw new SessionNotFoundException(sessionId); } @Inject SessionService(SamlEngineProxy samlEngineProxy,
TransactionsConfigProxy configProxy,
AuthnRequestFromTransactionHandler authnRequestHandler,
SessionRepository sessionRepository); SessionId create(final SamlAuthnRequestContainerDto requestDto); SessionId getSessionIfItExists(SessionId sessionId); Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId); AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId); AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId); AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId); }### Answer:
@Test public void getSession_ReturnSessionIdWhenSessionExists() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); assertThat(service.getSessionIfItExists(sessionId)).isEqualTo(sessionId); }
@Test(expected = SessionNotFoundException.class) public void getSession_ThrowsExceptionWhenSessionDoesNotExists() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(false); assertThat(service.getSessionIfItExists(sessionId)).isEqualTo(sessionId); } |
### Question:
SessionService { public AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId) { getSessionIfItExists(sessionId); if (authnRequestHandler.isResponseFromCountryWithUnsignedAssertions(sessionId)) { AuthnResponseFromCountryContainerDto authResponseFromCountryContainerDto = authnRequestHandler.getAuthnResponseFromCountryContainerDto(sessionId); return samlEngineProxy.generateRpAuthnResponseWrappingCountrySaml(authResponseFromCountryContainerDto); } ResponseFromHub responseFromHub = authnRequestHandler.getResponseFromHub(sessionId); return samlEngineProxy.generateRpAuthnResponse(responseFromHub); } @Inject SessionService(SamlEngineProxy samlEngineProxy,
TransactionsConfigProxy configProxy,
AuthnRequestFromTransactionHandler authnRequestHandler,
SessionRepository sessionRepository); SessionId create(final SamlAuthnRequestContainerDto requestDto); SessionId getSessionIfItExists(SessionId sessionId); Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId); AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId); AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId); AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId); }### Answer:
@Test(expected = SessionNotFoundException.class) public void shouldThrowSessionNotFoundWhenSessionDoesNotExistAndAResponseFromHubIsRequested() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(false); service.getRpAuthnResponse(sessionId); }
@Test public void shouldUpdateSessionStateAndCallSamlEngineWhenResponseFromHubIsRequested() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); ResponseFromHub responseFromHub = aResponseFromHubDto().build(); when(authnRequestHandler.getResponseFromHub(sessionId)).thenReturn(responseFromHub); AuthnResponseFromHubContainerDto expected = anAuthnResponseFromHubContainerDto().build(); when(samlEngineProxy.generateRpAuthnResponse(responseFromHub)).thenReturn(expected); AuthnResponseFromHubContainerDto actual = service.getRpAuthnResponse(sessionId); assertThat(actual).isEqualTo(expected); }
@Test public void shouldCallSamlEngineCountrySamlAuthnResponseGenerationEndpointIfIsResponseFromCountry() { ArgumentCaptor<AuthnResponseFromCountryContainerDto> capturedDto = ArgumentCaptor.forClass(AuthnResponseFromCountryContainerDto.class); AuthnResponseFromCountryContainerDto authnResponseFromCountryContainerDto = anAuthnResponseFromCountryContainerDto().build(); SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); when(authnRequestHandler.isResponseFromCountryWithUnsignedAssertions(sessionId)).thenReturn(true); when(authnRequestHandler.getAuthnResponseFromCountryContainerDto(sessionId)).thenReturn(authnResponseFromCountryContainerDto); service.getRpAuthnResponse(sessionId); verify(samlEngineProxy).generateRpAuthnResponseWrappingCountrySaml(capturedDto.capture()); assertThat(capturedDto.getValue()).isEqualTo(authnResponseFromCountryContainerDto); } |
### Question:
SessionService { public Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId){ getSessionIfItExists(sessionId); return sessionRepository.getLevelOfAssuranceFromIdp(sessionId); } @Inject SessionService(SamlEngineProxy samlEngineProxy,
TransactionsConfigProxy configProxy,
AuthnRequestFromTransactionHandler authnRequestHandler,
SessionRepository sessionRepository); SessionId create(final SamlAuthnRequestContainerDto requestDto); SessionId getSessionIfItExists(SessionId sessionId); Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId); AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId); AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId); AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId); }### Answer:
@Test public void shouldGetLevelOfAssurance() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); final Optional<LevelOfAssurance> loa = Optional.of(LevelOfAssurance.LEVEL_1); when(sessionRepository.getLevelOfAssuranceFromIdp(sessionId)).thenReturn(loa); assertThat(service.getLevelOfAssurance(sessionId)).isEqualTo(loa); } |
### Question:
SessionService { public AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId) { getSessionIfItExists(sessionId); final AuthnRequestFromHub request = authnRequestHandler.getIdaAuthnRequestFromHub(sessionId); final IdaAuthnRequestFromHubDto authnRequestFromHub = new IdaAuthnRequestFromHubDto( request.getId(), request.getForceAuthentication(), request.getSessionExpiryTimestamp(), request.getRecipientEntityId(), request.getLevelsOfAssurance(), request.getUseExactComparisonType(), request.getOverriddenSsoUrl()); boolean countryIdentityProvider = sessionRepository.isSessionInState(sessionId, EidasCountrySelectedState.class); final SamlRequestDto samlRequest; if (countryIdentityProvider) { samlRequest = samlEngineProxy.generateCountryAuthnRequestFromHub(authnRequestFromHub); EidasConnectorMetrics.increment( request.getRecipientEntityId(), EidasConnectorMetrics.Direction.request, EidasConnectorMetrics.Status.ok); } else { samlRequest = samlEngineProxy.generateIdpAuthnRequestFromHub(authnRequestFromHub); } return new AuthnRequestFromHubContainerDto(samlRequest.getSamlRequest(), samlRequest.getSsoUri(), request.getRegistering()); } @Inject SessionService(SamlEngineProxy samlEngineProxy,
TransactionsConfigProxy configProxy,
AuthnRequestFromTransactionHandler authnRequestHandler,
SessionRepository sessionRepository); SessionId create(final SamlAuthnRequestContainerDto requestDto); SessionId getSessionIfItExists(SessionId sessionId); Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId); AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId); AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId); AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId); }### Answer:
@Test public void shouldGetIdpAuthnRequest() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); AuthnRequestFromHub authnRequestFromHub = anAuthnRequestFromHub().build(); when(authnRequestHandler.getIdaAuthnRequestFromHub(sessionId)).thenReturn(authnRequestFromHub); URI ssoUri = UriBuilder.fromUri(UUID.randomUUID().toString()).build(); SamlRequestDto samlRequest = new SamlRequestDto("samlRequest", ssoUri); when(samlEngineProxy.generateIdpAuthnRequestFromHub(any(IdaAuthnRequestFromHubDto.class))).thenReturn(samlRequest); AuthnRequestFromHubContainerDto idpAuthnRequest = service.getIdpAuthnRequest(sessionId); AuthnRequestFromHubContainerDto expected = new AuthnRequestFromHubContainerDto(samlRequest.getSamlRequest(), ssoUri, authnRequestFromHub.getRegistering()); assertThat(idpAuthnRequest).isEqualToComparingFieldByField(expected); } |
### Question:
SessionService { public AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId) { getSessionIfItExists(sessionId); final ResponseFromHub errorResponseFromHub = authnRequestHandler.getErrorResponseFromHub(sessionId); final RequestForErrorResponseFromHubDto requestForErrorResponseFromHubDto = new RequestForErrorResponseFromHubDto(errorResponseFromHub.getAuthnRequestIssuerEntityId(), errorResponseFromHub.getResponseId(), errorResponseFromHub.getInResponseTo(), errorResponseFromHub.getAssertionConsumerServiceUri(), errorResponseFromHub.getStatus()); final SamlMessageDto samlMessageDto = samlEngineProxy.generateErrorResponseFromHub(requestForErrorResponseFromHubDto); final AuthnResponseFromHubContainerDto authnResponseFromHubContainerDto = new AuthnResponseFromHubContainerDto(samlMessageDto.getSamlMessage(), errorResponseFromHub.getAssertionConsumerServiceUri(), errorResponseFromHub.getRelayState(), errorResponseFromHub.getResponseId()); return authnResponseFromHubContainerDto; } @Inject SessionService(SamlEngineProxy samlEngineProxy,
TransactionsConfigProxy configProxy,
AuthnRequestFromTransactionHandler authnRequestHandler,
SessionRepository sessionRepository); SessionId create(final SamlAuthnRequestContainerDto requestDto); SessionId getSessionIfItExists(SessionId sessionId); Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId); AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId); AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId); AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId); }### Answer:
@Test(expected = ApplicationException.class) public void sendErrorResponseFromHub_shouldErrorWhenSamlEngineProxyReturnsAnError() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); ResponseFromHub responseFromHub = aResponseFromHubDto().withRelayState("relayState").build(); when(authnRequestHandler.getErrorResponseFromHub(sessionId)).thenReturn(responseFromHub); when(samlEngineProxy.generateErrorResponseFromHub(any())).thenThrow(ApplicationException.createAuditedException(ExceptionType.NETWORK_ERROR, UUID.randomUUID())); service.getRpErrorResponse(sessionId); } |
### Question:
MatchingServiceResponseService { public void handleSuccessResponse(SessionId sessionId, SamlResponseDto samlResponse) { getSessionIfItExists(sessionId); SamlResponseContainerDto samlResponseContainer = new SamlResponseContainerDto( samlResponse.getSamlResponse(), sessionRepository.getRequestIssuerEntityId(sessionId) ); try { InboundResponseFromMatchingServiceDto inboundResponseFromMatchingServiceDto = samlEngineProxy.translateMatchingServiceResponse(samlResponseContainer); updateSessionState(sessionId, inboundResponseFromMatchingServiceDto); } catch(ApplicationException e) { logExceptionAndUpdateState("Error translating matching service response", sessionId, e); } } @Inject MatchingServiceResponseService(SamlEngineProxy samlEngineProxy,
SessionRepository sessionRepository,
HubEventLogger eventLogger); void handleFailure(SessionId sessionId); void handleSuccessResponse(SessionId sessionId, SamlResponseDto samlResponse); }### Answer:
@Test(expected = SessionNotFoundException.class) public void handle_shouldThrowExceptionIfSessionDoesNotExist() { when(sessionRepository.sessionExists(sessionId)).thenReturn(false); matchingServiceResponseService.handleSuccessResponse(sessionId, samlResponseDto); }
@Test public void handle_shouldLogToEventSinkAndNotifyPolicyOnRequesterError() { final InboundResponseFromMatchingServiceDto inboundResponseFromMatchingServiceDto = new InboundResponseFromMatchingServiceDto(MatchingServiceIdaStatus.RequesterError, inResponseTo, "issuer", Optional.empty(), Optional.empty()); when(samlEngineProxy.translateMatchingServiceResponse(any())).thenReturn(inboundResponseFromMatchingServiceDto); matchingServiceResponseService.handleSuccessResponse(sessionId, samlResponseDto); verify(waitingForMatchingServiceResponseStateController, times(1)).handleRequestFailure(); verify(eventLogger).logErrorEvent(format("Requester error in response from matching service for session {0}", sessionId), sessionId); }
@Test public void handle_shouldUpdateStateWhenSamlProxyCannotProcessSaml() { when(samlEngineProxy.translateMatchingServiceResponse(any())).thenThrow(ApplicationException.createAuditedException(ExceptionType.INVALID_SAML, UUID.randomUUID())); matchingServiceResponseService.handleSuccessResponse(sessionId, samlResponseDto); verify(waitingForMatchingServiceResponseStateController, times(1)).handleRequestFailure(); verify(eventLogger).logErrorEvent("Error translating matching service response", sessionId); } |
### Question:
MatchingServiceResponseService { public void handleFailure(SessionId sessionId) { getSessionIfItExists(sessionId); logRequesterErrorAndUpdateState(sessionId, "received failure notification from saml-soap-proxy"); } @Inject MatchingServiceResponseService(SamlEngineProxy samlEngineProxy,
SessionRepository sessionRepository,
HubEventLogger eventLogger); void handleFailure(SessionId sessionId); void handleSuccessResponse(SessionId sessionId, SamlResponseDto samlResponse); }### Answer:
@Test(expected = SessionNotFoundException.class) public void handle_shouldThrowExceptionIfSessionDoesNotExistInMSResponseFailureCase() { when(sessionRepository.sessionExists(sessionId)).thenReturn(false); matchingServiceResponseService.handleFailure(sessionId); }
@Test public void handle_shouldLogToEventSinkAndUpdateStateWhenHandlingError() { matchingServiceResponseService.handleFailure(sessionId); verify(waitingForMatchingServiceResponseStateController, times(1)).handleRequestFailure(); verify(eventLogger).logErrorEvent(format("received failure notification from saml-soap-proxy for session {0}", sessionId), sessionId); } |
### Question:
LevelOfAssuranceValidator { public void validate(Optional<LevelOfAssurance> responseLevelOfAssurance, LevelOfAssurance requiredLevelOfAssurance) { if (!responseLevelOfAssurance.isPresent()) { throw noLevelOfAssurance(); } if (!responseLevelOfAssurance.get().equals(requiredLevelOfAssurance)) { throw wrongLevelOfAssurance(java.util.Optional.of(responseLevelOfAssurance.get()), singletonList(requiredLevelOfAssurance)); } } void validate(Optional<LevelOfAssurance> responseLevelOfAssurance, LevelOfAssurance requiredLevelOfAssurance); }### Answer:
@Test public void validate_shouldNotThrowExceptionIfLevelOfAssuranceFromMatchingServiceMatchesOneFromIdp() throws Exception { LevelOfAssurance levelOfAssurance = LevelOfAssurance.LEVEL_2; levelOfAssuranceValidator.validate(Optional.ofNullable(levelOfAssurance), levelOfAssurance); }
@Test public void validate_shouldThrowExceptionIfLevelOfAssuranceFromMatchingServiceDoesNotExist() throws Exception { LevelOfAssurance levelOfAssurance = LevelOfAssurance.LEVEL_2; try { levelOfAssuranceValidator.validate(Optional.empty(), levelOfAssurance); fail("fail"); } catch (StateProcessingValidationException e) { assertThat(e.getMessage()).isEqualTo(StateProcessingValidationException.noLevelOfAssurance().getMessage()); } }
@Test public void validate_shouldThrowExceptionIfLevelOfAssuranceFromMatchingServiceDoesNotMatchOneFromIdp() throws Exception { try { levelOfAssuranceValidator.validate(Optional.ofNullable(LevelOfAssurance.LEVEL_2), LevelOfAssurance.LEVEL_4); fail("fail"); } catch (StateProcessingValidationException e) { assertThat(e.getMessage()).isEqualTo(StateProcessingValidationException.wrongLevelOfAssurance(java.util.Optional.of(LevelOfAssurance.LEVEL_2), singletonList(LevelOfAssurance.LEVEL_4)).getMessage()); } } |
### Question:
ProtectiveMonitoringLogFormatter { public String formatAuthnRequest(AuthnRequest authnRequest, Direction direction, SignatureStatus signatureStatus) { Issuer issuer = authnRequest.getIssuer(); String issuerId = issuer != null ? issuer.getValue() : ""; return String.format(AUTHN_REQUEST, authnRequest.getID(), direction, authnRequest.getDestination(), issuerId, signatureStatus.valid()); } String formatAuthnRequest(AuthnRequest authnRequest, Direction direction, SignatureStatus signatureStatus); String formatAuthnResponse(Response samlResponse, Direction direction, SignatureStatus signatureStatus); }### Answer:
@Test public void shouldFormatAuthnRequest() { AuthnRequest authnRequest = anAuthnRequest().withId("test-id").withDestination("veganistan").build(); String logString = new ProtectiveMonitoringLogFormatter().formatAuthnRequest(authnRequest, Direction.INBOUND, SignatureStatus.VALID_SIGNATURE); String expectedLogMessage = "Protective Monitoring – Authn Request Event – {" + "requestId: test-id, " + "direction: INBOUND, " + "destination: veganistan, " + "issuerId: a-test-entity, " + "validSignature: true}"; assertThat(logString).isEqualTo(expectedLogMessage); }
@Test public void shouldFormatAuthnRequestWithoutIssuer() { AuthnRequest authnRequest = anAuthnRequest().withId("test-id").withDestination("veganistan").withIssuer(null).build(); String logString = new ProtectiveMonitoringLogFormatter().formatAuthnRequest(authnRequest, Direction.INBOUND, SignatureStatus.VALID_SIGNATURE); assertThat(logString).contains("issuerId: ,"); } |
### Question:
RedisSessionStore implements SessionStore { @Override public void insert(SessionId sessionId, State value) { dataStore.setex(sessionId, recordTTL, value); } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldInsertIntoRedisWithExpiry() { SessionId sessionId = aSessionId().build(); State state = getRandomState(); redisSessionStore.insert(sessionId, state); verify(redis).setex(sessionId, EXPIRY_TIME, state); } |
### Question:
RedisSessionStore implements SessionStore { @Override public void replace(SessionId sessionId, State value) { Long ttl = dataStore.ttl(sessionId); dataStore.setex(sessionId, ttl, value); } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldReplaceSessionInRedis() { SessionId sessionId = aSessionId().build(); State state = getRandomState(); redisSessionStore.replace(sessionId, state); verify(redis).setex(eq(sessionId), anyLong(), eq(state)); } |
### Question:
RedisSessionStore implements SessionStore { @Override public boolean hasSession(SessionId sessionId) { return dataStore.exists(sessionId) > 0; } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldCheckIfSessionExists() { SessionId sessionId = aSessionId().build(); redisSessionStore.hasSession(sessionId); verify(redis).exists(sessionId); } |
### Question:
RedisSessionStore implements SessionStore { @Override public State get(SessionId sessionId) { return dataStore.get(sessionId); } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldGetASessionFromRedis() { SessionId sessionId = aSessionId().build(); redisSessionStore.get(sessionId); verify(redis).get(sessionId); } |
### Question:
ResponseProcessingDetails { public SessionId getSessionId() { return sessionId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getSessionId() { assertThat(responseProcessingDetails.getSessionId()).isEqualTo(SESSION_ID); } |
### Question:
ResponseProcessingDetails { public ResponseProcessingStatus getResponseProcessingStatus() { return responseProcessingStatus; } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getResponseProcessingStatus() { assertThat(responseProcessingDetails.getResponseProcessingStatus()).isEqualTo(ResponseProcessingStatus.GET_C3_DATA); } |
### Question:
ResponseProcessingDetails { public String getTransactionEntityId() { return transactionEntityId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getTransactionEntityId() { assertThat(responseProcessingDetails.getTransactionEntityId()).isEqualTo(TRANSACTION_ENTITY_ID); } |
### Question:
ResponseProcessingDetails { @Override public String toString() { final StringBuilder sb = new StringBuilder("ResponseProcessingDetails{"); sb.append("sessionId=").append(sessionId); sb.append(", responseProcessingStatus=").append(responseProcessingStatus); sb.append(", transactionEntityId='").append(transactionEntityId).append('\''); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("ResponseProcessingDetails{"); sb.append("sessionId=").append(responseProcessingDetails.getSessionId()); sb.append(", responseProcessingStatus=").append(responseProcessingDetails.getResponseProcessingStatus()); sb.append(", transactionEntityId='").append(responseProcessingDetails.getTransactionEntityId()).append('\''); sb.append('}'); assertThat(responseProcessingDetails.toString()).isEqualTo(sb.toString()); } |
### Question:
ResponseFromHub { public String getAuthnRequestIssuerEntityId() { return authnRequestIssuerEntityId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAuthnRequestIssuerEntityId() { assertThat(responseFromHub.getAuthnRequestIssuerEntityId()).isEqualTo(AUTHN_REQUEST_ISSUER_ENTITY_ID); } |
### Question:
ResponseFromHub { public String getResponseId() { return responseId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getResponseId() { assertThat(responseFromHub.getResponseId()).isEqualTo(RESPONSE_ID); } |
### Question:
ResponseFromHub { public String getInResponseTo() { return inResponseTo; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getInResponseTo() { assertThat(responseFromHub.getInResponseTo()).isEqualTo(IN_RESPONSE_TO); } |
### Question:
ResponseFromHub { public List<String> getEncryptedAssertions() { return encryptedAssertions; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getEncryptedAssertions() { assertThat(responseFromHub.getEncryptedAssertions()).containsOnly(MATCHING_SERVICE_ASSERTION); } |
### Question:
ResponseFromHub { public Optional<String> getRelayState() { return relayState; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getRelayState() { assertThat(responseFromHub.getRelayState()).isEqualTo(RELAY_STATE); } |
### Question:
ResponseFromHub { public URI getAssertionConsumerServiceUri() { return assertionConsumerServiceUri; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAssertionConsumerServiceUri() { assertThat(responseFromHub.getAssertionConsumerServiceUri()).isEqualTo(ASSERTION_CONSUMER_SERVICE_URI); } |
### Question:
ResponseFromHub { public TransactionIdaStatus getStatus() { return status; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getStatus() { assertThat(responseFromHub.getStatus()).isEqualTo(TransactionIdaStatus.Success); } |
### Question:
ResponseFromHub { @Override public String toString() { final StandardToStringStyle style = new StandardToStringStyle(); style.setUseIdentityHashCode(false); return ReflectionToStringBuilder.toString(this, style); } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("uk.gov.ida.hub.policy.domain.ResponseFromHub["); sb.append("authnRequestIssuerEntityId=").append(responseFromHub.getAuthnRequestIssuerEntityId()); sb.append(",responseId=").append(responseFromHub.getResponseId()); sb.append(",inResponseTo=").append(responseFromHub.getInResponseTo()); sb.append(",status=").append(responseFromHub.getStatus()); sb.append(",encryptedAssertions=").append(responseFromHub.getEncryptedAssertions()); sb.append(",relayState=").append(responseFromHub.getRelayState()); sb.append(",assertionConsumerServiceUri=").append(responseFromHub.getAssertionConsumerServiceUri()); sb.append(']'); assertThat(responseFromHub.toString()).isEqualTo(sb.toString()); } |
### Question:
Cycle3Dataset implements Serializable { public Map<String, String> getAttributes() { return attributes; } @SuppressWarnings("unused")//Needed by JAXB private Cycle3Dataset(); Cycle3Dataset(Map<String, String> attributes); Map<String, String> getAttributes(); static Cycle3Dataset createFromData(String attributeKey, String userInputData); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAttributes() throws Exception { Cycle3Dataset cycle3Dataset = new Cycle3Dataset(map); assertThat(cycle3Dataset.getAttributes()).isEqualTo(map); } |
### Question:
Cycle3Dataset implements Serializable { public static Cycle3Dataset createFromData(String attributeKey, String userInputData) { Map<String, String> attributes = new HashMap<>(); attributes.put(attributeKey, userInputData); return new Cycle3Dataset(attributes); } @SuppressWarnings("unused")//Needed by JAXB private Cycle3Dataset(); Cycle3Dataset(Map<String, String> attributes); Map<String, String> getAttributes(); static Cycle3Dataset createFromData(String attributeKey, String userInputData); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void createFromData() throws Exception { Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData(DEFAULT_ATTRIBUTE, DEFAULT_ATTRIBUTE_VALUE); assertThat(cycle3Dataset.getAttributes()).isEqualTo(map); } |
### Question:
Cycle3Dataset implements Serializable { @Override public String toString() { final StringBuilder sb = new StringBuilder("Cycle3Dataset{"); sb.append("attributes=").append(attributes); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private Cycle3Dataset(); Cycle3Dataset(Map<String, String> attributes); Map<String, String> getAttributes(); static Cycle3Dataset createFromData(String attributeKey, String userInputData); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() throws Exception { final Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData(DEFAULT_ATTRIBUTE, DEFAULT_ATTRIBUTE_VALUE); final StringBuilder sb = new StringBuilder("Cycle3Dataset{"); sb.append("attributes=").append(cycle3Dataset.getAttributes()); sb.append('}'); assertThat(cycle3Dataset.toString()).isEqualTo(sb.toString()); } |
### Question:
EidasAuthnFailedErrorStateController extends AbstractAuthnFailedErrorStateController<EidasAuthnFailedErrorState> implements RestartJourneyStateController, EidasCountrySelectingStateController { @Override public void transitionToSessionStartedState() { final SessionStartedState sessionStartedState = createSessionStartedState(); hubEventLogger.logSessionMovedToStartStateEvent(sessionStartedState); stateTransitionAction.transitionTo(sessionStartedState); } EidasAuthnFailedErrorStateController(
EidasAuthnFailedErrorState state,
ResponseFromHubFactory responseFromHubFactory,
StateTransitionAction stateTransitionAction,
HubEventLogger hubEventLogger); @Override void transitionToSessionStartedState(); @Override void selectCountry(final String countryEntityId); }### Answer:
@Test public void shouldTransitionToSessionStartedStateAndLogEvent() { controller.transitionToSessionStartedState(); ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); verify(hubEventLogger, times(1)).logSessionMovedToStartStateEvent(capturedState.getValue()); assertThat(capturedState.getValue().getSessionId()).isEqualTo(eidasAuthnFailedErrorState.getSessionId()); assertThat(capturedState.getValue().getRequestIssuerEntityId()).isEqualTo(REQUEST_ISSUER_ID); assertThat(capturedState.getValue().getTransactionSupportsEidas()).isEqualTo(true); assertThat(capturedState.getValue().getForceAuthentication().orElse(null)).isEqualTo(true); } |
### Question:
AwaitingCycle3DataStateController extends AbstractAwaitingCycle3DataStateController<AttributeQueryRequestDto, AwaitingCycle3DataState> implements StateController, ResponseProcessingStateController, ErrorResponsePreparedStateController { @Override public void handleCycle3DataSubmitted(final String principalIpAddressAsSeenByHub) { getHubEventLogger().logCycle3DataObtained( getState().getSessionId(), getState().getRequestIssuerEntityId(), getState().getSessionExpiryTimestamp(), getState().getRequestId(), principalIpAddressAsSeenByHub ); Cycle3MatchRequestSentState cycle3MatchRequestSentState = new Cycle3MatchRequestSentState( getState().getRequestId(), getState().getRequestIssuerEntityId(), getState().getSessionExpiryTimestamp(), getState().getAssertionConsumerServiceUri(), getState().getSessionId(), getState().getTransactionSupportsEidas(), getState().getIdentityProviderEntityId(), getState().getRelayState().orElse(null), getState().getLevelOfAssurance(), getState().isRegistering(), getState().getMatchingServiceEntityId(), getState().getEncryptedMatchingDatasetAssertion(), getState().getAuthnStatementAssertion(), getState().getPersistentId() ); getStateTransitionAction().transitionTo(cycle3MatchRequestSentState); } AwaitingCycle3DataStateController(
final AwaitingCycle3DataState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final TransactionsConfigProxy transactionsConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final PolicyConfiguration policyConfiguration,
final AssertionRestrictionsFactory assertionRestrictionsFactory,
final MatchingServiceConfigProxy matchingServiceConfigProxy); @Override AttributeQueryRequestDto createAttributeQuery(final Cycle3Dataset cycle3Dataset); @Override void handleCycle3DataSubmitted(final String principalIpAddressAsSeenByHub); }### Answer:
@Test public void handleCycle3DataSubmitted_shouldLogCycle3DataObtainedAndPrincipalIpAddressSeenByHubToEventSink() { final SessionId sessionId = aSessionId().build(); final String principalIpAddressAsSeenByHub = "principal-ip-address-as-seen-by-hub"; final String requestId = "requestId"; final AwaitingCycle3DataStateController awaitingCycle3DataStateController = setUpAwaitingCycle3DataStateController(requestId, sessionId); awaitingCycle3DataStateController.handleCycle3DataSubmitted(principalIpAddressAsSeenByHub); ArgumentCaptor<EventSinkHubEvent> argumentCaptor = ArgumentCaptor.forClass(EventSinkHubEvent.class); verify(eventSinkProxy, atLeastOnce()).logHubEvent(argumentCaptor.capture()); Condition<EventSinkHubEvent> combinedConditions = AllOf.allOf( hasSessionId(sessionId), hasDetail(EventDetailsKey.session_event_type, CYCLE3_DATA_OBTAINED), hasDetail(EventDetailsKey.request_id, requestId), hasDetail(EventDetailsKey.principal_ip_address_as_seen_by_hub, principalIpAddressAsSeenByHub)); assertThat(argumentCaptor.getAllValues()).haveAtLeast(1, combinedConditions); }
@Test public void shouldMoveFromAwaitingC3StateToCycle3DataSentStateWhenCycle3DataIsReceived() { final SessionId sessionId = SessionId.createNewSessionId(); AwaitingCycle3DataState state = anAwaitingCycle3DataState().withSessionId(sessionId).build(); AwaitingCycle3DataStateController controller = new AwaitingCycle3DataStateController(state, hubEventLogger, stateTransitionAction, transactionsConfigProxy, responseFromHubFactory, policyConfiguration, assertionRestrictionsFactory, matchingServiceConfigProxy); ArgumentCaptor<Cycle3MatchRequestSentState> argumentCaptor = ArgumentCaptor.forClass(Cycle3MatchRequestSentState.class); controller.handleCycle3DataSubmitted("principalIpAsSeenByHub"); verify(stateTransitionAction, times(1)).transitionTo(argumentCaptor.capture()); final Cycle3MatchRequestSentState cycle3MatchRequestSentState = argumentCaptor.getValue(); assertThat(cycle3MatchRequestSentState.getEncryptedMatchingDatasetAssertion()).isEqualTo(state.getEncryptedMatchingDatasetAssertion()); } |
### Question:
SuccessfulMatchStateController extends AbstractSuccessfulMatchStateController<SuccessfulMatchState> { @Override public ResponseFromHub getPreparedResponse() { Collection<String> enabledIdentityProviders = identityProvidersConfigProxy.getEnabledIdentityProvidersForAuthenticationResponseProcessing( state.getRequestIssuerEntityId(), state.isRegistering(), state.getLevelOfAssurance()); if (!enabledIdentityProviders.contains(state.getIdentityProviderEntityId())) { throw new IdpDisabledException(state.getIdentityProviderEntityId()); } return getResponse(); } SuccessfulMatchStateController(
final SuccessfulMatchState state,
final ResponseFromHubFactory responseFromHubFactory,
final IdentityProvidersConfigProxy identityProvidersConfigProxy); @Override ResponseFromHub getPreparedResponse(); }### Answer:
@Test(expected = IdpDisabledException.class) public void getPreparedResponse_shouldThrowWhenIdpIsDisabled() { when(identityProvidersConfigProxy.getEnabledIdentityProvidersForAuthenticationResponseProcessing(any(String.class), anyBoolean(), any(LevelOfAssurance.class))) .thenReturn(emptyList()); controller.getPreparedResponse(); }
@Test public void getPreparedResponse_shouldReturnResponse() { final List<String> enabledIdentityProviders = singletonList(state.getIdentityProviderEntityId()); final ResponseFromHub expectedResponseFromHub = ResponseFromHubBuilder.aResponseFromHubDto().build(); when(identityProvidersConfigProxy.getEnabledIdentityProvidersForAuthenticationResponseProcessing(eq(state.getRequestIssuerEntityId()), anyBoolean(), any(LevelOfAssurance.class))) .thenReturn(enabledIdentityProviders); when(responseFromHubFactory.createSuccessResponseFromHub( state.getRequestId(), state.getMatchingServiceAssertion(), state.getRelayState(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri())) .thenReturn(expectedResponseFromHub); final ResponseFromHub result = controller.getPreparedResponse(); assertThat(result).isEqualTo(expectedResponseFromHub); } |
### Question:
IdpSelectedStateController implements ErrorResponsePreparedStateController, IdpSelectingStateController, AuthnRequestCapableController, RestartJourneyStateController { @Override public void transitionToSessionStartedState() { final SessionStartedState sessionStartedState = createSessionStartedState(); stateTransitionAction.transitionTo(sessionStartedState); hubEventLogger.logSessionMovedToStartStateEvent(sessionStartedState); } IdpSelectedStateController(
final IdpSelectedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final IdentityProvidersConfigProxy identityProvidersConfigProxy,
final TransactionsConfigProxy transactionsConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final PolicyConfiguration policyConfiguration,
final AssertionRestrictionsFactory assertionRestrictionsFactory,
final MatchingServiceConfigProxy matchingServiceConfigProxy); AuthnRequestFromHub getRequestFromHub(); void handleNoAuthenticationContextResponseFromIdp(AuthenticationErrorResponse authenticationErrorResponse); void handlePausedRegistrationResponseFromIdp(String requestIssuerEntityId, String principalIdAsSeenByHub, Optional<LevelOfAssurance> responseLoa, String analyticsSessionId, String journeyType); void handleAuthenticationFailedResponseFromIdp(AuthenticationErrorResponse authenticationErrorResponse); void handleRequesterErrorResponseFromIdp(RequesterErrorResponse requesterErrorResponseDto); void handleMatchingJourneySuccessResponseFromIdp(SuccessFromIdp successFromIdp); void handleNonMatchingJourneySuccessResponseFromIdp(SuccessFromIdp successFromIdp); void handleFraudResponseFromIdp(FraudFromIdp fraudFromIdp); AttributeQueryRequestDto createAttributeQuery(SuccessFromIdp successFromIdp); @Override ResponseFromHub getErrorResponse(); boolean isRegistrationContext(); String getMatchingServiceEntityId(); boolean isMatchingJourney(); @Override void handleIdpSelected(String idpEntityId, String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant); @Override String getRequestIssuerId(); @Override AuthnRequestSignInProcess getSignInProcessDetails(); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldTransitionToSessionStartedStateAndLogEvent() { controller.transitionToSessionStartedState(); ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); verify(hubEventLogger, times(1)).logSessionMovedToStartStateEvent(capturedState.getValue()); assertThat(capturedState.getValue().getSessionId()).isEqualTo(idpSelectedState.getSessionId()); assertThat(capturedState.getValue().getRequestIssuerEntityId()).isEqualTo(idpSelectedState.getRequestIssuerEntityId()); assertThat(capturedState.getValue().getForceAuthentication()).isEqualTo(idpSelectedState.getForceAuthentication()); } |
### Question:
IdpSelectedStateController implements ErrorResponsePreparedStateController, IdpSelectingStateController, AuthnRequestCapableController, RestartJourneyStateController { public String getMatchingServiceEntityId() { return transactionsConfigProxy.getMatchingServiceEntityId(state.getRequestIssuerEntityId()); } IdpSelectedStateController(
final IdpSelectedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final IdentityProvidersConfigProxy identityProvidersConfigProxy,
final TransactionsConfigProxy transactionsConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final PolicyConfiguration policyConfiguration,
final AssertionRestrictionsFactory assertionRestrictionsFactory,
final MatchingServiceConfigProxy matchingServiceConfigProxy); AuthnRequestFromHub getRequestFromHub(); void handleNoAuthenticationContextResponseFromIdp(AuthenticationErrorResponse authenticationErrorResponse); void handlePausedRegistrationResponseFromIdp(String requestIssuerEntityId, String principalIdAsSeenByHub, Optional<LevelOfAssurance> responseLoa, String analyticsSessionId, String journeyType); void handleAuthenticationFailedResponseFromIdp(AuthenticationErrorResponse authenticationErrorResponse); void handleRequesterErrorResponseFromIdp(RequesterErrorResponse requesterErrorResponseDto); void handleMatchingJourneySuccessResponseFromIdp(SuccessFromIdp successFromIdp); void handleNonMatchingJourneySuccessResponseFromIdp(SuccessFromIdp successFromIdp); void handleFraudResponseFromIdp(FraudFromIdp fraudFromIdp); AttributeQueryRequestDto createAttributeQuery(SuccessFromIdp successFromIdp); @Override ResponseFromHub getErrorResponse(); boolean isRegistrationContext(); String getMatchingServiceEntityId(); boolean isMatchingJourney(); @Override void handleIdpSelected(String idpEntityId, String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant); @Override String getRequestIssuerId(); @Override AuthnRequestSignInProcess getSignInProcessDetails(); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldReturnMatchingServiceEntityIdWhenAsked() { controller.getMatchingServiceEntityId(); verify(transactionsConfigProxy).getMatchingServiceEntityId(idpSelectedState.getRequestIssuerEntityId()); } |
### Question:
AuthnFailedErrorStateController extends AbstractAuthnFailedErrorStateController<AuthnFailedErrorState> implements IdpSelectingStateController { @Override public void handleIdpSelected(String idpEntityId, String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant) { IdpSelectedState idpSelectedState = IdpSelector.buildIdpSelectedState(state, idpEntityId, registering, requestedLoa, transactionsConfigProxy, identityProvidersConfigProxy); stateTransitionAction.transitionTo(idpSelectedState); hubEventLogger.logIdpSelectedEvent(idpSelectedState, principalIpAddress, analyticsSessionId, journeyType, abTestVariant); } AuthnFailedErrorStateController(
AuthnFailedErrorState state,
ResponseFromHubFactory responseFromHubFactory,
StateTransitionAction stateTransitionAction,
TransactionsConfigProxy transactionsConfigProxy,
IdentityProvidersConfigProxy identityProvidersConfigProxy,
HubEventLogger hubEventLogger); FailureResponseDetails handleFailureResponse(); void tryAnotherIdpResponse(); @Override void handleIdpSelected(String idpEntityId, String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant); @Override String getRequestIssuerId(); @Override AuthnRequestSignInProcess getSignInProcessDetails(); }### Answer:
@Test public void handleIdpSelect_shouldTransitionStateAndLogEvent() { controller.handleIdpSelected(IDP_ENTITY_ID, "some-ip-address", false, LevelOfAssurance.LEVEL_2, "some-analytics-session-id", "some-journey-type", abTestVariant); ArgumentCaptor<IdpSelectedState> capturedState = ArgumentCaptor.forClass(IdpSelectedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); assertThat(capturedState.getValue().getIdpEntityId()).isEqualTo(IDP_ENTITY_ID); assertThat(capturedState.getValue().getLevelsOfAssurance()).containsSequence(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_2); verify(hubEventLogger, times(1)).logIdpSelectedEvent(capturedState.getValue(), "some-ip-address", "some-analytics-session-id", "some-journey-type", abTestVariant); }
@Test public void idpSelect_shouldThrowWhenIdentityProviderInvalid() { try { controller.handleIdpSelected("notExist", "some-ip-address", REGISTERING, LevelOfAssurance.LEVEL_2, "some-analytics-session-id", "some-journey-type", abTestVariant); fail("Should throw StateProcessingValidationException"); } catch(StateProcessingValidationException e) { assertThat(e.getMessage()).contains("Available Identity Provider for session ID [" + authnFailedErrorState .getSessionId().getSessionId() + "] not found for entity ID [notExist]."); verify(hubEventLogger, times(0)).logIdpSelectedEvent(any(IdpSelectedState.class), eq("some-ip-address"), eq("some-analytics-session-id"), eq("some-journey-type"), eq(abTestVariant)); } } |
### Question:
AuthnFailedErrorStateController extends AbstractAuthnFailedErrorStateController<AuthnFailedErrorState> implements IdpSelectingStateController { public void tryAnotherIdpResponse() { stateTransitionAction.transitionTo(createSessionStartedState()); } AuthnFailedErrorStateController(
AuthnFailedErrorState state,
ResponseFromHubFactory responseFromHubFactory,
StateTransitionAction stateTransitionAction,
TransactionsConfigProxy transactionsConfigProxy,
IdentityProvidersConfigProxy identityProvidersConfigProxy,
HubEventLogger hubEventLogger); FailureResponseDetails handleFailureResponse(); void tryAnotherIdpResponse(); @Override void handleIdpSelected(String idpEntityId, String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant); @Override String getRequestIssuerId(); @Override AuthnRequestSignInProcess getSignInProcessDetails(); }### Answer:
@Test public void tryAnotherIdpResponse_shouldTransitionToSessionStartedState() { ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); SessionStartedState expectedState = aSessionStartedState(). withSessionId(aSessionId().with("sessionId").build()) .withForceAuthentication(true) .withTransactionSupportsEidas(true) .withSessionExpiryTimestamp(NOW) .withAssertionConsumerServiceUri(URI.create("/default-service-index")) .build(); controller.tryAnotherIdpResponse(); verify(stateTransitionAction).transitionTo(capturedState.capture()); assertThat(capturedState.getValue()).isInstanceOf(SessionStartedState.class); assertThat(capturedState.getValue()).isEqualToComparingFieldByField(expectedState); } |
### Question:
ProtectiveMonitoringLogger { public void logAuthnResponse(Response samlResponse, Direction direction, SignatureStatus signatureStatus) { Map<String, String> copyOfContextMap = Optional.ofNullable(MDC.getCopyOfContextMap()).orElse(Collections.emptyMap()); StatusCode statusCode = samlResponse.getStatus().getStatusCode(); MDC.setContextMap(Map.of( "responseId", samlResponse.getID(), "inResponseTo", samlResponse.getInResponseTo(), "status", statusCode.getValue(), "subStatus", Optional.ofNullable(statusCode.getStatusCode()).map(StatusCode::getValue).orElse("NoSubStatus"), "direction", direction.name(), "issuerId", Optional.ofNullable(samlResponse.getIssuer()).map(Issuer::getValue).orElse("NoIssuer"), "destination", Optional.ofNullable(samlResponse.getDestination()).orElse("NoDestination"), "signatureStatus", signatureStatus.name())); LOG.info(formatter.formatAuthnResponse(samlResponse, direction, signatureStatus)); MDC.clear(); MDC.setContextMap(copyOfContextMap); } @Inject ProtectiveMonitoringLogger(ProtectiveMonitoringLogFormatter formatter); void logAuthnRequest(AuthnRequest request, Direction direction, SignatureStatus signatureStatus); void logAuthnResponse(Response samlResponse, Direction direction, SignatureStatus signatureStatus); }### Answer:
@Test public void shouldLogWhenNoSignatureExists() { ProtectiveMonitoringLogger protectiveMonitoringLogger = new ProtectiveMonitoringLogger(new ProtectiveMonitoringLogFormatter()); when(samlResponse.getStatus()).thenReturn(status); when(samlResponse.getID()).thenReturn("ID"); when(samlResponse.getInResponseTo()).thenReturn("InResponseTo"); when(status.getStatusCode()).thenReturn(statusCode); when(statusCode.getValue()).thenReturn("all-good"); protectiveMonitoringLogger.logAuthnResponse(samlResponse, Direction.OUTBOUND, SignatureStatus.NO_SIGNATURE); assertThat(TestAppender.events.size()).isEqualTo(1); assertThat(TestAppender.events.get(0).getMDCPropertyMap()).contains( MapEntry.entry("signatureStatus", "NO_SIGNATURE") ); }
@Test public void shouldLogWhenSignatureIsPresentAndCorrect() { ProtectiveMonitoringLogger protectiveMonitoringLogger = new ProtectiveMonitoringLogger(new ProtectiveMonitoringLogFormatter()); when(samlResponse.getStatus()).thenReturn(status); when(samlResponse.getID()).thenReturn("ID"); when(samlResponse.getInResponseTo()).thenReturn("InResponseTo"); when(status.getStatusCode()).thenReturn(statusCode); when(statusCode.getValue()).thenReturn("all-good"); protectiveMonitoringLogger.logAuthnResponse(samlResponse, Direction.OUTBOUND, SignatureStatus.VALID_SIGNATURE); assertThat(TestAppender.events.size()).isEqualTo(1); assertThat(TestAppender.events.get(0).getMDCPropertyMap()).contains( MapEntry.entry("signatureStatus", "VALID_SIGNATURE") ); }
@Test public void shouldLogWhenSignatureIsPresentButInvalid() { ProtectiveMonitoringLogger protectiveMonitoringLogger = new ProtectiveMonitoringLogger(new ProtectiveMonitoringLogFormatter()); when(samlResponse.getStatus()).thenReturn(status); when(samlResponse.getID()).thenReturn("ID"); when(samlResponse.getInResponseTo()).thenReturn("InResponseTo"); when(status.getStatusCode()).thenReturn(statusCode); when(statusCode.getValue()).thenReturn("all-good"); protectiveMonitoringLogger.logAuthnResponse(samlResponse, Direction.OUTBOUND, SignatureStatus.INVALID_SIGNATURE); assertThat(TestAppender.events.size()).isEqualTo(1); assertThat(TestAppender.events.get(0).getMDCPropertyMap()).contains( MapEntry.entry("signatureStatus", "INVALID_SIGNATURE") ); } |
### Question:
SessionStartedStateController implements IdpSelectingStateController, EidasCountrySelectingStateController, ResponseProcessingStateController, ErrorResponsePreparedStateController { @Override public void handleIdpSelected(final String idpEntityId, final String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant) { IdpSelectedState idpSelectedState = IdpSelector.buildIdpSelectedState(state, idpEntityId, registering, requestedLoa, transactionsConfigProxy, identityProvidersConfigProxy); stateTransitionAction.transitionTo(idpSelectedState); hubEventLogger.logIdpSelectedEvent(idpSelectedState, principalIpAddress, analyticsSessionId, journeyType, abTestVariant); } SessionStartedStateController(
final SessionStartedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final TransactionsConfigProxy transactionsConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final IdentityProvidersConfigProxy identityProvidersConfigProxy); @Override AuthnRequestSignInProcess getSignInProcessDetails(); @Override String getRequestIssuerId(); @Override void handleIdpSelected(final String idpEntityId, final String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant); @Override ResponseProcessingDetails getResponseProcessingDetails(); @Override ResponseFromHub getErrorResponse(); @Override void selectCountry(String countryEntityId); }### Answer:
@Test public void handleIdpSelect_shouldTransitionStateAndLogEvent() { controller.handleIdpSelected(IDP_ENTITY_ID, "some-ip-address", REGISTERING, LevelOfAssurance.LEVEL_2, "some-analytics-session-id", "some-journey-id", AB_TEST_VARIANT); ArgumentCaptor<IdpSelectedState> capturedState = ArgumentCaptor.forClass(IdpSelectedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); assertThat(capturedState.getValue().getIdpEntityId()).isEqualTo(IDP_ENTITY_ID); assertThat(capturedState.getValue().getLevelsOfAssurance()).containsSequence(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_2); assertThat(capturedState.getValue().getTransactionSupportsEidas()).isTrue(); verify(hubEventLogger, times(1)).logIdpSelectedEvent(capturedState.getValue(), "some-ip-address", "some-analytics-session-id", "some-journey-id", AB_TEST_VARIANT); }
@Test public void idpSelect_shouldThrowWhenIdentityProviderInvalid() { try { controller.handleIdpSelected("notExist", "some-ip-address", false, LevelOfAssurance.LEVEL_2, "some-analytics-session-id", "some-journey-id", AB_TEST_VARIANT); fail("Should throw StateProcessingValidationException"); } catch(StateProcessingValidationException e) { assertThat(e.getMessage()).contains("Available Identity Provider for session ID [" + sessionStartedState .getSessionId().getSessionId() + "] not found for entity ID [notExist]."); verify(hubEventLogger, times(0)).logIdpSelectedEvent(any(IdpSelectedState.class), eq("some-ip-address"),eq("some-analytics-session-id"), eq("some-journey-id"), eq(AB_TEST_VARIANT)); } } |
### Question:
SessionStartedStateController implements IdpSelectingStateController, EidasCountrySelectingStateController, ResponseProcessingStateController, ErrorResponsePreparedStateController { @Override public void selectCountry(String countryEntityId) { EidasCountrySelectedState eidasCountrySelectedState = new EidasCountrySelectedState( countryEntityId, state.getRelayState().orElse(null), state.getRequestId(), state.getRequestIssuerEntityId(), state.getSessionExpiryTimestamp(), state.getAssertionConsumerServiceUri(), state.getSessionId(), state.getTransactionSupportsEidas(), Collections.singletonList(LevelOfAssurance.LEVEL_2), state.getForceAuthentication().orElse(null) ); stateTransitionAction.transitionTo(eidasCountrySelectedState); hubEventLogger.logCountrySelectedEvent(eidasCountrySelectedState); } SessionStartedStateController(
final SessionStartedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final TransactionsConfigProxy transactionsConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final IdentityProvidersConfigProxy identityProvidersConfigProxy); @Override AuthnRequestSignInProcess getSignInProcessDetails(); @Override String getRequestIssuerId(); @Override void handleIdpSelected(final String idpEntityId, final String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant); @Override ResponseProcessingDetails getResponseProcessingDetails(); @Override ResponseFromHub getErrorResponse(); @Override void selectCountry(String countryEntityId); }### Answer:
@Test public void selectCountry_shouldTransitionStateAndLogEvent() { controller.selectCountry("DE"); ArgumentCaptor<EidasCountrySelectedState> capturedState = ArgumentCaptor.forClass(EidasCountrySelectedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); assertThat(capturedState.getValue().getLevelsOfAssurance()).containsSequence(LevelOfAssurance.LEVEL_2); assertThat(capturedState.getValue().getTransactionSupportsEidas()).isTrue(); assertThat(capturedState.getValue().getForceAuthentication().orElse(null)).isFalse(); verify(hubEventLogger, times(1)).logCountrySelectedEvent(capturedState.getValue()); } |
### Question:
EidasAwaitingCycle3DataStateController extends AbstractAwaitingCycle3DataStateController<EidasAttributeQueryRequestDto, EidasAwaitingCycle3DataState> implements StateController, ResponseProcessingStateController, ErrorResponsePreparedStateController { @Override public EidasAttributeQueryRequestDto createAttributeQuery(final Cycle3Dataset cycle3Dataset) { MatchingServiceConfigEntityDataDto matchingServiceConfigData = getMatchingServiceConfigProxy().getMatchingService(getState().getMatchingServiceEntityId()); URI matchingServiceAdapterUri = matchingServiceConfigData.getUri(); return new EidasAttributeQueryRequestDto( getState().getRequestId(), getState().getRequestIssuerEntityId(), getState().getAssertionConsumerServiceUri(), getAssertionRestrictionsFactory().getAssertionExpiry(), getState().getMatchingServiceEntityId(), matchingServiceAdapterUri, DateTime.now().plus(getPolicyConfiguration().getMatchingServiceResponseWaitPeriod()), matchingServiceConfigData.isOnboarding(), getState().getLevelOfAssurance(), getState().getPersistentId(), Optional.ofNullable(cycle3Dataset), Optional.empty(), getState().getEncryptedIdentityAssertion(), getState().getCountrySignedResponseContainer() ); } EidasAwaitingCycle3DataStateController(
final EidasAwaitingCycle3DataState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final TransactionsConfigProxy transactionsConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final PolicyConfiguration policyConfiguration,
final AssertionRestrictionsFactory assertionRestrictionsFactory,
final MatchingServiceConfigProxy matchingServiceConfigProxy); @Override EidasAttributeQueryRequestDto createAttributeQuery(final Cycle3Dataset cycle3Dataset); @Override void handleCycle3DataSubmitted(final String principalIpAddressAsSeenByHub); }### Answer:
@Test public void createAttributeQuery() { final Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData("attribute", "attributeValue"); final MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = aMatchingServiceConfigEntityDataDto() .withEntityId(state.getMatchingServiceEntityId()) .build(); when(matchingServiceConfigProxy.getMatchingService(state.getMatchingServiceEntityId())).thenReturn(matchingServiceConfigEntityDataDto); when(policyConfiguration.getMatchingServiceResponseWaitPeriod()).thenReturn(Duration.standardMinutes(60)); when(assertionRestrictionsFactory.getAssertionExpiry()).thenReturn(DateTime.now().plusHours(2)); final EidasAttributeQueryRequestDto expectedDto = new EidasAttributeQueryRequestDto( state.getRequestId(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri(), assertionRestrictionsFactory.getAssertionExpiry(), state.getMatchingServiceEntityId(), matchingServiceConfigEntityDataDto.getUri(), DateTime.now().plus(policyConfiguration.getMatchingServiceResponseWaitPeriod()), matchingServiceConfigEntityDataDto.isOnboarding(), state.getLevelOfAssurance(), state.getPersistentId(), Optional.of(cycle3Dataset), Optional.empty(), state.getEncryptedIdentityAssertion(), Optional.empty() ); EidasAttributeQueryRequestDto actualDto = controller.createAttributeQuery(cycle3Dataset); assertThat(actualDto).isEqualTo(expectedDto); } |
### Question:
EidasAwaitingCycle3DataStateController extends AbstractAwaitingCycle3DataStateController<EidasAttributeQueryRequestDto, EidasAwaitingCycle3DataState> implements StateController, ResponseProcessingStateController, ErrorResponsePreparedStateController { @Override public void handleCycle3DataSubmitted(final String principalIpAddressAsSeenByHub) { getHubEventLogger().logCycle3DataObtained( getState().getSessionId(), getState().getRequestIssuerEntityId(), getState().getSessionExpiryTimestamp(), getState().getRequestId(), principalIpAddressAsSeenByHub ); EidasCycle3MatchRequestSentState eidasCycle3MatchRequestSentState = new EidasCycle3MatchRequestSentState( getState().getRequestId(), getState().getRequestIssuerEntityId(), getState().getSessionExpiryTimestamp(), getState().getAssertionConsumerServiceUri(), getState().getSessionId(), getState().getTransactionSupportsEidas(), getState().getIdentityProviderEntityId(), getState().getRelayState().orElse(null), getState().getLevelOfAssurance(), getState().getMatchingServiceEntityId(), getState().getEncryptedIdentityAssertion(), getState().getPersistentId(), getState().getForceAuthentication().orElse(null), getState().getCountrySignedResponseContainer().orElse(null) ); getStateTransitionAction().transitionTo(eidasCycle3MatchRequestSentState); } EidasAwaitingCycle3DataStateController(
final EidasAwaitingCycle3DataState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final TransactionsConfigProxy transactionsConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final PolicyConfiguration policyConfiguration,
final AssertionRestrictionsFactory assertionRestrictionsFactory,
final MatchingServiceConfigProxy matchingServiceConfigProxy); @Override EidasAttributeQueryRequestDto createAttributeQuery(final Cycle3Dataset cycle3Dataset); @Override void handleCycle3DataSubmitted(final String principalIpAddressAsSeenByHub); }### Answer:
@Test public void shouldTransitionToEidasCycle3MatchRequestSentState() { final String principalIpAddressAsSeenByHub = "principalIpAddressAsSeenByHub"; doNothing().when(hubEventLogger).logCycle3DataObtained( state.getSessionId(), state.getRequestIssuerEntityId(), state.getSessionExpiryTimestamp(), state.getRequestId(), principalIpAddressAsSeenByHub ); final EidasCycle3MatchRequestSentState expectedState = new EidasCycle3MatchRequestSentState( state.getRequestId(), state.getRequestIssuerEntityId(), state.getSessionExpiryTimestamp(), state.getAssertionConsumerServiceUri(), state.getSessionId(), state.getTransactionSupportsEidas(), state.getIdentityProviderEntityId(), state.getRelayState().orElse(null), state.getLevelOfAssurance(), state.getMatchingServiceEntityId(), state.getEncryptedIdentityAssertion(), state.getPersistentId(), state.getForceAuthentication().orElse(null), state.getCountrySignedResponseContainer().orElse(null) ); controller.handleCycle3DataSubmitted(principalIpAddressAsSeenByHub); verify(stateTransitionAction).transitionTo(expectedState); } |
### Question:
EidasSuccessfulMatchStateController extends AbstractSuccessfulMatchStateController<EidasSuccessfulMatchState> { @Override public ResponseFromHub getPreparedResponse() { List<EidasCountryDto> enabledCountries = countriesService.getCountries(state.getSessionId()); if (enabledCountries.stream().noneMatch(country -> country.getEntityId().equals(state.getIdentityProviderEntityId()))) { throw new IdpDisabledException(state.getIdentityProviderEntityId()); } return getResponse(); } EidasSuccessfulMatchStateController(
EidasSuccessfulMatchState state,
ResponseFromHubFactory responseFromHubFactory,
CountriesService countriesService); @Override ResponseFromHub getPreparedResponse(); }### Answer:
@Test(expected = IdpDisabledException.class) public void getPreparedResponse_shouldThrowWhenCountryIsDisabled() { when(countriesService.getCountries(state.getSessionId())) .thenReturn(emptyList()); controller.getPreparedResponse(); }
@Test public void shouldReturnPreparedResponse() { List<EidasCountryDto> enabledIdentityProviders = singletonList(new EidasCountryDto("country-entity-id", "simple-id", true)); ResponseFromHub expectedResponseFromHub = ResponseFromHubBuilder.aResponseFromHubDto().build(); when(countriesService.getCountries(state.getSessionId())) .thenReturn(enabledIdentityProviders); when(responseFromHubFactory.createSuccessResponseFromHub( state.getRequestId(), state.getMatchingServiceAssertion(), state.getRelayState(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri())) .thenReturn(expectedResponseFromHub); ResponseFromHub result = controller.getPreparedResponse(); assertThat(result).isEqualTo(expectedResponseFromHub); } |
### Question:
EidasUserAccountCreationFailedStateController extends AbstractUserAccountCreationFailedStateController<EidasUserAccountCreationFailedState> implements RestartJourneyStateController { @Override public void transitionToSessionStartedState() { final SessionStartedState sessionStartedState = createSessionStartedState(); hubEventLogger.logSessionMovedToStartStateEvent(sessionStartedState); stateTransitionAction.transitionTo(sessionStartedState); } EidasUserAccountCreationFailedStateController(
final EidasUserAccountCreationFailedState state,
final ResponseFromHubFactory responseFromHubFactory,
final StateTransitionAction stateTransitionAction,
HubEventLogger hubEventLogger); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldTransitionToSessionStartedStateAndLogEvent() { controller.transitionToSessionStartedState(); ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); verify(hubEventLogger, times(1)).logSessionMovedToStartStateEvent(capturedState.getValue()); assertThat(capturedState.getValue().getSessionId()).isEqualTo(eidasUserAccountCreationFailedState.getSessionId()); assertThat(capturedState.getValue().getRequestIssuerEntityId()).isEqualTo(REQUEST_ISSUER_ID); assertThat(capturedState.getValue().getTransactionSupportsEidas()).isEqualTo(true); assertThat(capturedState.getValue().getForceAuthentication().orElse(null)).isEqualTo(false); } |
### Question:
ConfigServiceKeyStore { public List<PublicKey> getVerifyingKeysForEntity(String entityId) { Collection<CertificateDto> certificates = certificatesConfigProxy.getSignatureVerificationCertificates(entityId); List<PublicKey> publicKeys = new ArrayList<>(); for (CertificateDto keyFromConfig : certificates) { String base64EncodedCertificateValue = keyFromConfig.getCertificate(); final X509Certificate certificate = x509CertificateFactory.createCertificate(base64EncodedCertificateValue); trustStoreForCertificateProvider.getTrustStoreFor(keyFromConfig.getFederationEntityType()) .ifPresent(keyStore -> validate(certificate, keyStore)); publicKeys.add(certificate.getPublicKey()); } return publicKeys; } @Inject ConfigServiceKeyStore(
CertificatesConfigProxy certificatesConfigProxy,
CertificateChainValidator certificateChainValidator,
TrustStoreForCertificateProvider trustStoreForCertificateProvider,
X509CertificateFactory x509CertificateFactory); List<PublicKey> getVerifyingKeysForEntity(String entityId); PublicKey getEncryptionKeyForEntity(String entityId); }### Answer:
@Test public void getVerifyingKeysForEntity_shouldGetVerifyingKeysFromConfigCertificateProxy() { configServiceKeyStore.getVerifyingKeysForEntity(issuerId); verify(certificatesConfigProxy).getSignatureVerificationCertificates(issuerId); } |
### Question:
EidasCountrySelectedStateController implements ErrorResponsePreparedStateController, EidasCountrySelectingStateController, AuthnRequestCapableController, RestartJourneyStateController { public String getMatchingServiceEntityId() { return transactionsConfigProxy.getMatchingServiceEntityId(state.getRequestIssuerEntityId()); } EidasCountrySelectedStateController(
final EidasCountrySelectedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final PolicyConfiguration policyConfiguration,
final TransactionsConfigProxy transactionsConfigProxy,
final MatchingServiceConfigProxy matchingServiceConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final AssertionRestrictionsFactory assertionRestrictionFactory); String getMatchingServiceEntityId(); String getRequestIssuerId(); boolean isMatchingJourney(); String getCountryEntityId(); AuthnRequestFromHub getRequestFromHub(); EidasAttributeQueryRequestDto getEidasAttributeQueryRequestDto(InboundResponseFromCountry translatedResponse); @Override ResponseFromHub getErrorResponse(); @Override void selectCountry(String countryEntityId); void handleMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleNonMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleAuthenticationFailedResponseFromCountry(String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldReturnMatchingServiceEntityIdWhenAsked() { controller.getMatchingServiceEntityId(); verify(transactionsConfigProxy).getMatchingServiceEntityId(state.getRequestIssuerEntityId()); } |
### Question:
SamlProxyConfiguration extends Configuration implements RestfulClientConfiguration, TrustStoreConfiguration, ServiceNameConfiguration, PrometheusConfiguration { public Optional<CountryConfiguration> getCountryConfiguration() { return Optional.ofNullable(country); } protected SamlProxyConfiguration(); SamlConfiguration getSamlConfiguration(); Duration getMetadataValidDuration(); URI getFrontendExternalUri(); URI getPolicyUri(); MetadataResolverConfiguration getMetadataConfiguration(); @Override JerseyClientConfiguration getJerseyClientConfiguration(); URI getEventSinkUri(); URI getConfigUri(); Duration getCertificatesConfigCacheExpiry(); ServiceInfoConfiguration getServiceInfo(); @Override String getServiceName(); @Override ClientTrustStoreConfiguration getRpTrustStoreConfiguration(); @Override boolean getEnableRetryTimeOutConnections(); Optional<CountryConfiguration> getCountryConfiguration(); EventEmitterConfiguration getEventEmitterConfiguration(); boolean isEidasEnabled(); @Override boolean isPrometheusEnabled(); @Valid
@JsonProperty
public EventEmitterConfiguration eventEmitterConfiguration; }### Answer:
@Test public void shouldReturnCountryConfigOptionalIfCountryConfigNotNull() { SamlProxyConfiguration samlProxyConfiguration = new SamlProxyConfiguration(); CountryConfiguration countryConfiguration = new CountryConfiguration(null); samlProxyConfiguration.country = countryConfiguration; assertThat(samlProxyConfiguration.getCountryConfiguration()).isEqualTo(Optional.of(countryConfiguration)); }
@Test public void shouldReturnEmptyOptionalIfCountConfigNull() { SamlProxyConfiguration samlProxyConfiguration = new SamlProxyConfiguration(); assertThat(samlProxyConfiguration.getCountryConfiguration()).isEqualTo(Optional.empty()); } |
### Question:
EidasCountrySelectedStateController implements ErrorResponsePreparedStateController, EidasCountrySelectingStateController, AuthnRequestCapableController, RestartJourneyStateController { @Override public ResponseFromHub getErrorResponse() { return responseFromHubFactory.createNoAuthnContextResponseFromHub( state.getRequestId(), state.getRelayState(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri()); } EidasCountrySelectedStateController(
final EidasCountrySelectedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final PolicyConfiguration policyConfiguration,
final TransactionsConfigProxy transactionsConfigProxy,
final MatchingServiceConfigProxy matchingServiceConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final AssertionRestrictionsFactory assertionRestrictionFactory); String getMatchingServiceEntityId(); String getRequestIssuerId(); boolean isMatchingJourney(); String getCountryEntityId(); AuthnRequestFromHub getRequestFromHub(); EidasAttributeQueryRequestDto getEidasAttributeQueryRequestDto(InboundResponseFromCountry translatedResponse); @Override ResponseFromHub getErrorResponse(); @Override void selectCountry(String countryEntityId); void handleMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleNonMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleAuthenticationFailedResponseFromCountry(String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldReturnNoAuthContextErrorResponse() { ResponseFromHub errorResponse = controller.getErrorResponse(); assertThat(errorResponse).isNotNull(); assertThat(errorResponse.getStatus()).isEqualTo(TransactionIdaStatus.NoAuthenticationContext); assertThat(errorResponse.getAuthnRequestIssuerEntityId()).isEqualTo(state.getRequestIssuerEntityId()); assertThat(errorResponse.getInResponseTo()).isEqualTo(state.getRequestId()); assertThat(errorResponse.getRelayState()).isEqualTo(state.getRelayState()); assertThat(errorResponse.getAssertionConsumerServiceUri()).isEqualTo(state.getAssertionConsumerServiceUri()); } |
### Question:
EidasCountrySelectedStateController implements ErrorResponsePreparedStateController, EidasCountrySelectingStateController, AuthnRequestCapableController, RestartJourneyStateController { @Override public void transitionToSessionStartedState() { final SessionStartedState sessionStartedState = createSessionStartedState(); hubEventLogger.logSessionMovedToStartStateEvent(sessionStartedState); stateTransitionAction.transitionTo(sessionStartedState); } EidasCountrySelectedStateController(
final EidasCountrySelectedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final PolicyConfiguration policyConfiguration,
final TransactionsConfigProxy transactionsConfigProxy,
final MatchingServiceConfigProxy matchingServiceConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final AssertionRestrictionsFactory assertionRestrictionFactory); String getMatchingServiceEntityId(); String getRequestIssuerId(); boolean isMatchingJourney(); String getCountryEntityId(); AuthnRequestFromHub getRequestFromHub(); EidasAttributeQueryRequestDto getEidasAttributeQueryRequestDto(InboundResponseFromCountry translatedResponse); @Override ResponseFromHub getErrorResponse(); @Override void selectCountry(String countryEntityId); void handleMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleNonMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleAuthenticationFailedResponseFromCountry(String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldTransitionToSessionStartedStateAndLogEvent() { controller.transitionToSessionStartedState(); ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); verify(hubEventLogger, times(1)).logSessionMovedToStartStateEvent(capturedState.getValue()); assertThat(capturedState.getValue().getSessionId()).isEqualTo(state.getSessionId()); assertThat(capturedState.getValue().getRequestIssuerEntityId()).isEqualTo(state.getRequestIssuerEntityId()); assertThat(capturedState.getValue().getTransactionSupportsEidas()).isEqualTo(true); assertThat(capturedState.getValue().getForceAuthentication().orElse(null)).isEqualTo(false); } |
### Question:
Cycle3AttributeRequestData { public String getAttributeName() { return attributeName; } @SuppressWarnings("unused")//Needed by JAXB private Cycle3AttributeRequestData(); Cycle3AttributeRequestData(
final String attributeName,
final String requestIssuerId); String getAttributeName(); String getRequestIssuerId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAttributeName() { assertThat(cycle3AttributeRequestData.getAttributeName()).isEqualTo(CYCLE_3_ATTRIBUTE_NAME); } |
### Question:
Cycle3AttributeRequestData { public String getRequestIssuerId() { return requestIssuerId; } @SuppressWarnings("unused")//Needed by JAXB private Cycle3AttributeRequestData(); Cycle3AttributeRequestData(
final String attributeName,
final String requestIssuerId); String getAttributeName(); String getRequestIssuerId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getRequestIssuerId() { assertThat(cycle3AttributeRequestData.getRequestIssuerId()).isEqualTo(REQUEST_ISSUER_ENTITY_ID); } |
### Question:
Cycle3AttributeRequestData { @Override public String toString() { final StringBuilder sb = new StringBuilder("Cycle3AttributeRequestData{"); sb.append("attributeName='").append(attributeName).append('\''); sb.append(", requestIssuerId='").append(requestIssuerId).append('\''); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private Cycle3AttributeRequestData(); Cycle3AttributeRequestData(
final String attributeName,
final String requestIssuerId); String getAttributeName(); String getRequestIssuerId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("Cycle3AttributeRequestData{"); sb.append("attributeName='").append(cycle3AttributeRequestData.getAttributeName()).append('\''); sb.append(", requestIssuerId='").append(cycle3AttributeRequestData.getRequestIssuerId()).append('\''); sb.append('}'); assertThat(cycle3AttributeRequestData.toString()).isEqualTo(sb.toString()); } |
### Question:
SessionRepository { @Timed(name =Urls.SESSION_REPO_TIMED_GROUP) public Optional<LevelOfAssurance> getLevelOfAssuranceFromIdp(SessionId sessionId){ State currentState = getCurrentState(sessionId); if(currentState instanceof Cycle0And1MatchRequestSentState){ return Optional.of(((Cycle0And1MatchRequestSentState) currentState).getIdpLevelOfAssurance()); } if(currentState instanceof SuccessfulMatchState){ return Optional.of(((SuccessfulMatchState) currentState).getLevelOfAssurance()); } if(currentState instanceof AwaitingCycle3DataState){ return Optional.of(((AwaitingCycle3DataState) currentState).getLevelOfAssurance()); } if(currentState instanceof UserAccountCreatedState){ return Optional.of(((UserAccountCreatedState) currentState).getLevelOfAssurance()); } return Optional.empty(); } @Inject SessionRepository(
SessionStore dataStore,
StateControllerFactory controllerFactory); SessionId createSession(SessionStartedState startedState); @Timed(name = Urls.SESSION_REPO_TIMED_GROUP) StateController getStateController(
final SessionId sessionId,
final Class<T> expectedStateClass); @Timed(name = Urls.SESSION_REPO_TIMED_GROUP) boolean sessionExists(SessionId sessionId); @Timed(name =Urls.SESSION_REPO_TIMED_GROUP) Optional<LevelOfAssurance> getLevelOfAssuranceFromIdp(SessionId sessionId); boolean getTransactionSupportsEidas(SessionId sessionId); String getRequestIssuerEntityId(SessionId sessionId); boolean isSessionInState(SessionId sessionId, Class<? extends State> stateClass); void validateSessionExists(SessionId sessionId); }### Answer:
@Test public void getLevelOfAssuranceFromIdp(){ SessionStartedState state = aSessionStartedState().build(); SessionId sessionId = sessionRepository.createSession(state); assertThat(sessionRepository.getLevelOfAssuranceFromIdp(sessionId)).isEqualTo(Optional.empty()); } |
### Question:
PersistentId implements Serializable { public String getNameId() { return nameId; } @SuppressWarnings("unused")//Needed by JAXB private PersistentId(); @JsonCreator PersistentId(@JsonProperty("nameId") String nameId); String getNameId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getNameId() { assertThat(persistentId.getNameId()).isEqualTo(NAME_ID); } |
### Question:
PersistentId implements Serializable { @Override public String toString() { final StringBuilder sb = new StringBuilder("PersistentId{"); sb.append("nameId='").append(nameId).append('\''); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private PersistentId(); @JsonCreator PersistentId(@JsonProperty("nameId") String nameId); String getNameId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("PersistentId{"); sb.append("nameId='").append(NAME_ID).append('\''); sb.append('}'); assertThat(persistentId.toString()).isEqualTo(sb.toString()); } |
### Question:
EidasAttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { public String getEncryptedIdentityAssertion() { return encryptedIdentityAssertion; } EidasAttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedIdentityAssertion,
final Optional<CountrySignedResponseContainer> countrySignedResponseContainer); String getEncryptedIdentityAssertion(); Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); }### Answer:
@Test public void getEncryptedIdentityAssertion() throws Exception { assertThat(eidasAttributeQueryRequestDto.getEncryptedIdentityAssertion()).isEqualTo(ENCRYPTED_IDENTITY_ASSERTION); } |
### Question:
EidasAttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { @Override public AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy) { return samlEngineProxy.generateEidasAttributeQuery(this); } EidasAttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedIdentityAssertion,
final Optional<CountrySignedResponseContainer> countrySignedResponseContainer); String getEncryptedIdentityAssertion(); Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); }### Answer:
@Test public void sendToSamlEngine() throws Exception { when(samlEngineProxy.generateEidasAttributeQuery(eidasAttributeQueryRequestDto)).thenReturn(ATTRIBUTE_QUERY_CONTAINER_DTO); AttributeQueryContainerDto actual = eidasAttributeQueryRequestDto.sendToSamlEngine(samlEngineProxy); assertThat(actual).isEqualTo(ATTRIBUTE_QUERY_CONTAINER_DTO); } |
### Question:
EidasAttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { public Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer() { return countrySignedResponseContainer; } EidasAttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedIdentityAssertion,
final Optional<CountrySignedResponseContainer> countrySignedResponseContainer); String getEncryptedIdentityAssertion(); Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); }### Answer:
@Test public void getCountrySignedResponseContainer() { assertThat(eidasAttributeQueryRequestDto.getCountrySignedResponseContainer()).isEqualTo(COUNTRY_SIGNED_RESPONSE); } |
### Question:
EidasAttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { @Override public String toString() { final StringBuilder sb = new StringBuilder("EidasAttributeQueryRequestDto{"); sb.append(super.toString()); sb.append(",encryptedIdentityAssertion='").append(encryptedIdentityAssertion).append('\''); sb.append(",countrySignedResponseContainer='").append(countrySignedResponseContainer).append('\''); sb.append('}'); return sb.toString(); } EidasAttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedIdentityAssertion,
final Optional<CountrySignedResponseContainer> countrySignedResponseContainer); String getEncryptedIdentityAssertion(); Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("EidasAttributeQueryRequestDto{"); sb.append("requestId='").append(REQUEST_ID).append('\''); sb.append(",authnRequestIssuerEntityId='").append(AUTHN_REQUEST_ISSUER_ENTITY_ID).append('\''); sb.append(",assertionConsumerServiceUri=").append(ASSERTION_CONSUMER_SERVICE_URI); sb.append(",assertionExpiry=").append(ASSERTION_EXPIRY); sb.append(",matchingServiceEntityId='").append(MATCHING_SERVICE_ADAPTER_ENTITY_ID).append('\''); sb.append(",attributeQueryUri=").append(MATCHING_SERVICE_ADAPTER_URI); sb.append(",matchingServiceRequestTimeOut=").append(MATCHING_SERVICE_REQUEST_TIME_OUT); sb.append(",onboarding=").append(ONBOARDING); sb.append(",levelOfAssurance=").append(LevelOfAssurance.LEVEL_2); sb.append(",persistentId=").append(PERSISTENT_ID); sb.append(",cycle3Dataset=").append(CYCLE_3_DATASET); sb.append(",userAccountCreationAttributes=").append(USER_ACCOUNT_CREATION_ATTRIBUTES); sb.append(",encryptedIdentityAssertion='").append(ENCRYPTED_IDENTITY_ASSERTION).append('\''); sb.append(",countrySignedResponseContainer='").append(COUNTRY_SIGNED_RESPONSE).append('\''); sb.append('}'); assertThat(eidasAttributeQueryRequestDto.toString()).isEqualTo(sb.toString()); } |
### Question:
AttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { @Nullable public String getEncryptedMatchingDatasetAssertion() { return encryptedMatchingDatasetAssertion; } AttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedMatchingDatasetAssertion,
final String encryptedAuthnAssertion); static AttributeQueryRequestDto createCycle3MatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String encryptedAuthnAssertion,
Cycle3Dataset cycle3Assertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); static AttributeQueryRequestDto createCycle01MatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String encryptedAuthnAssertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); static AttributeQueryRequestDto createUserAccountRequiredMatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String authnStatementAssertion,
Optional<Cycle3Dataset> cycle3Assertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
List<UserAccountCreationAttribute> userAccountCreationAttributes,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); String getEncryptedAuthnAssertion(); @Nullable String getEncryptedMatchingDatasetAssertion(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getEncryptedMatchingDataSetAssertion() throws Exception { assertThat(attributeQueryRequestDto.getEncryptedMatchingDatasetAssertion()).isEqualTo(ENCRYPTED_MATCHING_DATASET_ASSERTION); } |
### Question:
AttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { public String getEncryptedAuthnAssertion() { return encryptedAuthnAssertion; } AttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedMatchingDatasetAssertion,
final String encryptedAuthnAssertion); static AttributeQueryRequestDto createCycle3MatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String encryptedAuthnAssertion,
Cycle3Dataset cycle3Assertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); static AttributeQueryRequestDto createCycle01MatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String encryptedAuthnAssertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); static AttributeQueryRequestDto createUserAccountRequiredMatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String authnStatementAssertion,
Optional<Cycle3Dataset> cycle3Assertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
List<UserAccountCreationAttribute> userAccountCreationAttributes,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); String getEncryptedAuthnAssertion(); @Nullable String getEncryptedMatchingDatasetAssertion(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAuthnStatementAssertion() throws Exception { assertThat(attributeQueryRequestDto.getEncryptedAuthnAssertion()).isEqualTo(AUTHN_STATEMENT_ASSERTION); } |
### Question:
AttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { @Override public AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy) { return samlEngineProxy.generateAttributeQuery(this); } AttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedMatchingDatasetAssertion,
final String encryptedAuthnAssertion); static AttributeQueryRequestDto createCycle3MatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String encryptedAuthnAssertion,
Cycle3Dataset cycle3Assertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); static AttributeQueryRequestDto createCycle01MatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String encryptedAuthnAssertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); static AttributeQueryRequestDto createUserAccountRequiredMatchingServiceRequest(
String requestId,
String encryptedMatchingDatasetAssertion,
String authnStatementAssertion,
Optional<Cycle3Dataset> cycle3Assertion,
String authnRequestIssuerEntityId,
URI assertionConsumerServiceUri,
String matchingServiceEntityId,
DateTime matchingServiceRequestTimeOut,
LevelOfAssurance levelOfAssurance,
List<UserAccountCreationAttribute> userAccountCreationAttributes,
PersistentId persistentId,
DateTime assertionExpiry,
URI attributeQueryUri,
boolean onboarding); String getEncryptedAuthnAssertion(); @Nullable String getEncryptedMatchingDatasetAssertion(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void sendToSamlEngine() throws Exception { when(samlEngineProxy.generateAttributeQuery(attributeQueryRequestDto)).thenReturn(ATTRIBUTE_QUERY_CONTAINER_DTO); AttributeQueryContainerDto actual = attributeQueryRequestDto.sendToSamlEngine(samlEngineProxy); assertThat(actual).isEqualTo(ATTRIBUTE_QUERY_CONTAINER_DTO); } |
### Question:
ManagedEntityConfigRepository implements ConfigRepository<T> { public Optional<T> get(String entityId) { return localConfigRepository.getData(entityId) .map(this::overrideWithRemote); } @Inject ManagedEntityConfigRepository(LocalConfigRepository<T> localConfigRepository, S3ConfigSource s3ConfigSource); Collection<T> getAll(); boolean has(String entityId); Optional<T> get(String entityId); Stream<T> stream(); }### Answer:
@Test public void getReturnsOptionalEmptyIfNoLocalConfigFound() { ManagedEntityConfigRepository<TransactionConfig> configRepo = new ManagedEntityConfigRepository<>(localConfigRepository, s3ConfigSource); Optional<TransactionConfig> result = configRepo.get(BAD_ENTITY_ID); assertThat(result).isNotPresent(); }
@Test public void getReturnsOptionalEmptyIfNoLocalConfigFoundButRemoteExists() { ManagedEntityConfigRepository<TransactionConfig> configRepo = new ManagedEntityConfigRepository<>(localConfigRepository, s3ConfigSource); Optional<TransactionConfig> result = configRepo.get(REMOTE_ONLY_ENTITY_ID); assertThat(result).isNotPresent(); } |
### Question:
IdaResponseFromIdpUnmarshaller { public InboundResponseFromIdp fromSaml(ValidatedResponse validatedResponse, ValidatedAssertions validatedAssertions) { Optional<PassthroughAssertion> matchingDatasetAssertion = validatedAssertions.getMatchingDatasetAssertion() .map(passthroughAssertionUnmarshaller::fromAssertion); Optional<PassthroughAssertion> authnStatementAssertion = validatedAssertions.getAuthnStatementAssertion() .map(passthroughAssertionUnmarshaller::fromAssertion); IdpIdaStatus transformedStatus = statusUnmarshaller.fromSaml(validatedResponse.getStatus()); URI destination = URI.create(validatedResponse.getDestination()); Optional<DateTime> notOnOrAfter = validatedAssertions.getMatchingDatasetAssertion() .flatMap(a -> Optional.ofNullable(a.getSubject())) .flatMap(s -> Optional.ofNullable(s.getSubjectConfirmations().get(0).getSubjectConfirmationData().getNotOnOrAfter())); return new InboundResponseFromIdp( validatedResponse.getID(), validatedResponse.getInResponseTo(), validatedResponse.getIssuer().getValue(), validatedResponse.getIssueInstant(), notOnOrAfter, transformedStatus, Optional.ofNullable(validatedResponse.getSignature()), matchingDatasetAssertion, destination, authnStatementAssertion); } IdaResponseFromIdpUnmarshaller(
IdpIdaStatusUnmarshaller statusUnmarshaller,
PassthroughAssertionUnmarshaller passthroughAssertionUnmarshaller); InboundResponseFromIdp fromSaml(ValidatedResponse validatedResponse, ValidatedAssertions validatedAssertions); }### Answer:
@Test public void transform_shouldTransformTheSamlResponseToIdaResponseByIdp() throws Exception { Assertion mdsAssertion = anAssertion().addAttributeStatement(anAttributeStatement().build()).buildUnencrypted(); Assertion authnStatementAssertion = anAssertion().addAuthnStatement(anAuthnStatement().build()).buildUnencrypted(); when(response.getAssertions()).thenReturn(List.of(mdsAssertion, authnStatementAssertion)); PassthroughAssertion passthroughMdsAssertion = aPassthroughAssertion().buildMatchingDatasetAssertion(); when(passthroughAssertionUnmarshaller.fromAssertion(mdsAssertion)).thenReturn(passthroughMdsAssertion); PassthroughAssertion passthroughAuthnAssertion = aPassthroughAssertion().buildAuthnStatementAssertion(); when(passthroughAssertionUnmarshaller.fromAssertion(authnStatementAssertion)).thenReturn(passthroughAuthnAssertion); InboundResponseFromIdp inboundResponseFromIdp = unmarshaller.fromSaml(new ValidatedResponse(response), new ValidatedAssertions(response.getAssertions())); assertThat(inboundResponseFromIdp.getSignature().isPresent()).isEqualTo(true); assertThat(inboundResponseFromIdp.getMatchingDatasetAssertion().isPresent()).isEqualTo(true); assertThat(inboundResponseFromIdp.getAuthnStatementAssertion().isPresent()).isEqualTo(true); assertThat(inboundResponseFromIdp.getSignature().get()).isEqualTo(signature); assertThat(inboundResponseFromIdp.getAuthnStatementAssertion().get()).isEqualTo(passthroughAuthnAssertion); assertThat(inboundResponseFromIdp.getMatchingDatasetAssertion().get()).isEqualTo(passthroughMdsAssertion); } |
### Question:
AuthnRequestFromRelyingPartyUnmarshaller { public AuthnRequestFromRelyingParty fromSamlMessage(AuthnRequest authnRequest) { final String id = authnRequest.getID(); final String issuerId = authnRequest.getIssuer().getValue(); final DateTime issueInstant = authnRequest.getIssueInstant(); final Boolean forceAuthn = authnRequest.isForceAuthn(); final Optional<String> assertionConsumerServiceURL = Optional.ofNullable(authnRequest.getAssertionConsumerServiceURL()); final Integer assertionConsumerServiceIndex = authnRequest.getAssertionConsumerServiceIndex(); final Signature signature = authnRequest.getSignature(); final Optional<String> verifyServiceProviderVersion = extractVerifyServiceProviderVersion(authnRequest.getExtensions(), issuerId); return new AuthnRequestFromRelyingParty( id, issuerId, issueInstant, URI.create(authnRequest.getDestination()), Optional.ofNullable(forceAuthn), assertionConsumerServiceURL.map(URI::create), ofNullable(assertionConsumerServiceIndex), ofNullable(signature), verifyServiceProviderVersion ); } AuthnRequestFromRelyingPartyUnmarshaller(Decrypter decrypter); AuthnRequestFromRelyingParty fromSamlMessage(AuthnRequest authnRequest); }### Answer:
@Test public void fromSamlMessage_shouldMapAuthnRequestToAuthnRequestFromRelyingParty() throws Exception { DateTime issueInstant = new DateTime(); SignatureImpl signature = new SignatureBuilder().buildObject(); AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject(); authnRequest.setID("some-id"); Issuer issuer = new IssuerBuilder().buildObject(); issuer.setValue("some-service-entity-id"); authnRequest.setIssuer(issuer); authnRequest.setIssueInstant(issueInstant); authnRequest.setDestination("http: authnRequest.setForceAuthn(true); authnRequest.setAssertionConsumerServiceURL("some-url"); authnRequest.setAssertionConsumerServiceIndex(5); authnRequest.setSignature(signature); authnRequest.setExtensions(createApplicationVersionExtensions("some-version")); AuthnRequestFromRelyingParty authnRequestFromRelyingParty = unmarshaller.fromSamlMessage(authnRequest); AuthnRequestFromRelyingParty expected = new AuthnRequestFromRelyingParty( "some-id", "some-service-entity-id", issueInstant, URI.create("http: Optional.of(true), Optional.of(URI.create("some-url")), Optional.of(5), Optional.of(signature), Optional.of("some-version") ); assertThat(authnRequestFromRelyingParty).isEqualTo(expected); }
@Test public void fromSamlMessage_shouldNotComplainWhenThereIsNoExtensionsElement() throws Exception { AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject(); authnRequest.setIssuer(new IssuerBuilder().buildObject()); authnRequest.setDestination("http: AuthnRequestFromRelyingParty authnRequestFromRelyingParty = unmarshaller.fromSamlMessage(authnRequest); assertThat(authnRequestFromRelyingParty.getVerifyServiceProviderVersion()).isEqualTo(Optional.empty()); }
@Test public void fromSamlMessage_shouldNotComplainWhenExceptionDuringDecryption() throws Exception { AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject(); authnRequest.setIssuer(new IssuerBuilder().buildObject()); authnRequest.setDestination("http: authnRequest.setExtensions(createApplicationVersionExtensions(null)); AuthnRequestFromRelyingParty authnRequestFromRelyingParty = unmarshaller.fromSamlMessage(authnRequest); assertThat(authnRequestFromRelyingParty.getVerifyServiceProviderVersion()).isEqualTo(Optional.empty()); } |
### Question:
IdpIdaStatusMarshaller extends IdaStatusMarshaller<IdpIdaStatus> { @Override protected Optional<StatusDetail> getStatusDetail(IdpIdaStatus originalStatus) { if (REST_TO_STATUS_DETAIL.containsKey(originalStatus)) { StatusDetail statusDetail = this.samlObjectFactory.createStatusDetail(); StatusValue statusValue = this.samlObjectFactory.createStatusValue(REST_TO_STATUS_DETAIL.get(originalStatus)); statusDetail.getUnknownXMLObjects().add(statusValue); return of(statusDetail); } return empty(); } IdpIdaStatusMarshaller(OpenSamlXmlObjectFactory samlObjectFactory); }### Answer:
@Test public void transform_shouldTransformAuthenticationPending() throws Exception { Status transformedStatus = marshaller.toSamlStatus(IdpIdaStatus.authenticationPending()); StatusValue actual = (StatusValue) transformedStatus.getStatusDetail().getOrderedChildren().get(0); assertThat(transformedStatus.getStatusCode().getValue()).isEqualTo(StatusCode.RESPONDER); assertThat(transformedStatus.getStatusCode().getStatusCode().getValue()).isEqualTo(StatusCode.NO_AUTHN_CONTEXT); assertThat(actual.getValue()).isEqualTo(StatusValue.PENDING); }
@Test public void shouldMarshallStatusDetailElementWhenInCancelStatus() { Status status = marshaller.toSamlStatus(IdpIdaStatus.authenticationCancelled()); assertThat(status.getStatusDetail()).isNotNull(); }
@Test public void shouldMarshallStatusDetailWithStatusValueContainingAuthnCancelInCaseOfAuthenticationCancelled() { Status status = marshaller.toSamlStatus(IdpIdaStatus.authenticationCancelled()); StatusValue actual = (StatusValue) status.getStatusDetail().getOrderedChildren().get(0); assertThat(actual.getNamespaces()).isEmpty(); assertThat(actual.getValue()).isEqualTo(StatusValue.CANCEL); }
@Test public void shouldMarshallStatusDetailWithStatusValueContainingUpliftFailed() { Status status = marshaller.toSamlStatus(IdpIdaStatus.upliftFailed()); StatusValue actual = (StatusValue) status.getStatusDetail().getOrderedChildren().get(0); assertThat(actual.getNamespaces()).isEmpty(); assertThat(actual.getValue()).isEqualTo(StatusValue.UPLIFT_FAILED); }
@Test public void shouldMarshallStatusDetailWithASingleStatusValueElementInCaseOfAuthenticationCancelled() { Status status = marshaller.toSamlStatus(IdpIdaStatus.authenticationCancelled()); assertThat(status.getStatusDetail().getOrderedChildren()).hasSize(1); } |
### Question:
IdpIdaStatusMarshaller extends IdaStatusMarshaller<IdpIdaStatus> { @Override protected Optional<String> getStatusMessage(IdpIdaStatus originalStatus) { return originalStatus.getMessage(); } IdpIdaStatusMarshaller(OpenSamlXmlObjectFactory samlObjectFactory); }### Answer:
@Test public void transform_shouldTransformRequesterErrorWithMessage() throws Exception { String message = "Oh dear"; Status transformedStatus = marshaller.toSamlStatus(IdpIdaStatus.requesterError(Optional.of(message))); assertThat(transformedStatus.getStatusCode().getValue()).isEqualTo(StatusCode.REQUESTER); assertThat(transformedStatus.getStatusMessage().getMessage()).isEqualTo(message); } |
### Question:
LevelsOfAssuranceConfigValidator { protected void validateAllIDPsSupportLOA1orLOA2(Set<IdentityProviderConfig> identityProviderConfig) { List<IdentityProviderConfig> badIDPConfigs = identityProviderConfig.stream() .filter(x -> x.getSupportedLevelsOfAssurance().isEmpty() || containsUnsupportedLOAs(x)) .collect(Collectors.toList()); if(!badIDPConfigs.isEmpty()) { throw ConfigValidationException.createIDPLevelsOfAssuranceUnsupportedException(badIDPConfigs); } } void validateLevelsOfAssurance(final Set<IdentityProviderConfig> identityProviderConfig,
final Set<TransactionConfig> transactionConfig); }### Answer:
@Test public void checkIDPConfigIsWithinVerifyPolicyLevelsOfAssurance() { Set<IdentityProviderConfig> identityProviderConfig = Set.of(loa1And2Idp); levelsOfAssuranceConfigValidator.validateAllIDPsSupportLOA1orLOA2(identityProviderConfig); }
@Test public void shouldAllowSingleLevelOfAssurance() { Set<IdentityProviderConfig> identityProviderConfig = Set.of(loa1Idp); levelsOfAssuranceConfigValidator.validateAllIDPsSupportLOA1orLOA2(identityProviderConfig); }
@Test(expected = ConfigValidationException.class) public void checkValidationThrowsExceptionWhenIDPSupportsAnLOAThatIsOutsideVerifyPolicyLevelsOfAssurance() { Set<IdentityProviderConfig> identityProviderConfig = Set.of(loa1To3Idp); levelsOfAssuranceConfigValidator.validateAllIDPsSupportLOA1orLOA2(identityProviderConfig); } |
### Question:
HubAssertionMarshaller { public Assertion toSaml(HubAssertion hubAssertion) { Assertion transformedAssertion = openSamlXmlObjectFactory.createAssertion(); transformedAssertion.setIssueInstant(hubAssertion.getIssueInstant()); Issuer transformedIssuer = openSamlXmlObjectFactory.createIssuer(hubAssertion.getIssuerId()); transformedAssertion.setIssuer(transformedIssuer); transformedAssertion.setID(hubAssertion.getId()); if (hubAssertion.getCycle3Data().isPresent()){ Cycle3Dataset cycle3Data = hubAssertion.getCycle3Data().get(); transformedAssertion.getAttributeStatements().add(transform(cycle3Data)); } transformedAssertion.setSubject(outboundAssertionToSubjectTransformer.transform(hubAssertion)); return transformedAssertion; } HubAssertionMarshaller(
OpenSamlXmlObjectFactory openSamlXmlObjectFactory,
AttributeFactory attributeFactory,
OutboundAssertionToSubjectTransformer outboundAssertionToSubjectTransformer); Assertion toSaml(HubAssertion hubAssertion); }### Answer:
@Test public void transform_shouldTransformAssertionId() throws Exception { String assertionId = "assertion-id"; HubAssertion assertion = aHubAssertion().withId(assertionId).build(); Assertion transformedAssertion = marshaller.toSaml(assertion); assertThat(transformedAssertion.getID()).isEqualTo(assertionId); }
@Test public void transform_shouldTransformAssertionIssuer() throws Exception { String assertionIssuerId = "assertion issuer"; HubAssertion assertion = aHubAssertion().withIssuerId(assertionIssuerId).build(); Assertion transformedAssertion = marshaller.toSaml(assertion); assertThat(transformedAssertion.getIssuer().getValue()).isEqualTo(assertionIssuerId); }
@Test public void transform_shouldTransformAssertionIssuerInstance() throws Exception { DateTime issueInstant = DateTime.parse("2012-12-31T12:34:56Z"); HubAssertion assertion = aHubAssertion().withIssueInstant(issueInstant).build(); Assertion transformedAssertion = marshaller.toSaml(assertion); assertThat(transformedAssertion.getIssueInstant()).isEqualTo(issueInstant); }
@Test public void transform_shouldTransformCycle3DataAssertion() throws Exception { String attributeName = "someName"; String value = "some value"; HubAssertion assertion = aHubAssertion().withCycle3Data(aCycle3Dataset().addCycle3Data(attributeName, value).build()).build(); Attribute expectedAttribute = aSimpleStringAttribute().build(); when(attributeFactory.createCycle3DataAttribute(attributeName, value)).thenReturn(expectedAttribute); Assertion transformedAssertion = marshaller.toSaml(assertion); List<AttributeStatement> attributeStatements = transformedAssertion.getAttributeStatements(); assertThat(attributeStatements.size()).isGreaterThan(0); Attribute attribute = attributeStatements.get(0).getAttributes().get(0); assertThat(attribute).isEqualTo(expectedAttribute); }
@Test public void transform_shouldTransformLevelOfCycle3DataAssertion() throws Exception { String attributeName = "someName"; String value = "some value"; HubAssertion assertion = aHubAssertion().withCycle3Data(aCycle3Dataset().addCycle3Data(attributeName, value).build()).build(); Attribute expectedAttribute = aSimpleStringAttribute().build(); when(attributeFactory.createCycle3DataAttribute(attributeName, value)).thenReturn(expectedAttribute); Assertion transformedAssertion = marshaller.toSaml(assertion); List<AttributeStatement> attributeStatements = transformedAssertion.getAttributeStatements(); assertThat(attributeStatements.size()).isGreaterThan(0); Attribute attribute = attributeStatements.get(0).getAttributes().get(0); assertThat(attribute).isEqualTo(expectedAttribute); } |
### Question:
OutboundResponseFromHubToSamlResponseTransformer extends IdaResponseToSamlResponseTransformer<OutboundResponseFromHub> { @Override protected void transformAssertions(OutboundResponseFromHub originalResponse, Response transformedResponse) { originalResponse .getEncryptedAssertions().stream() .map(encryptedAssertionUnmarshaller::transform) .forEach(transformedResponse.getEncryptedAssertions()::add); } OutboundResponseFromHubToSamlResponseTransformer(
IdaStatusMarshaller<TransactionIdaStatus> statusMarshaller,
OpenSamlXmlObjectFactory openSamlXmlObjectFactory,
EncryptedAssertionUnmarshaller encryptedAssertionUnmarshaller); }### Answer:
@Test public void transformAssertions_shouldTransformMatchingServiceAssertions() throws Exception { PassthroughAssertion matchingServiceAssertion = aPassthroughAssertion().buildMatchingServiceAssertion(); Response transformedResponse = aResponse().withNoDefaultAssertion().build(); EncryptedAssertion transformedMatchingDatasetAssertion = anAssertion().build(); when(encryptedAssertionUnmarshaller.transform(matchingServiceAssertion.getUnderlyingAssertionBlob())).thenReturn(transformedMatchingDatasetAssertion); String encryptedMatchingServiceAssertion = matchingServiceAssertion.getUnderlyingAssertionBlob(); transformer.transformAssertions(anAuthnResponse().withEncryptedAssertions(Collections.singletonList(encryptedMatchingServiceAssertion)).buildOutboundResponseFromHub(), transformedResponse); assertThat(transformedResponse.getEncryptedAssertions().size()).isEqualTo(1); assertThat(transformedResponse.getEncryptedAssertions().get(0)).isEqualTo(transformedMatchingDatasetAssertion); } |
### Question:
EncryptedAssertionUnmarshaller { public EncryptedAssertion transform(String assertionString) { EncryptedAssertion assertion = stringAssertionTransformer.apply(assertionString); assertion.detach(); return assertion; } EncryptedAssertionUnmarshaller(StringToOpenSamlObjectTransformer<EncryptedAssertion> stringAssertionTransformer); EncryptedAssertion transform(String assertionString); }### Answer:
@Test public void shouldCreateAEncryptedAssertionObjectFromAGivenString() throws Exception { EncryptedAssertionUnmarshaller encryptedAssertionUnmarshaller = new EncryptedAssertionUnmarshaller(stringToEncryptedAssertionTransformer); final EncryptedAssertion expected = new EncryptedAssertionBuilder().buildObject(); when(stringToEncryptedAssertionTransformer.apply(ENCRYPTED_ASSERTION_BLOB)).thenReturn(expected); final EncryptedAssertion encryptedAssertion = encryptedAssertionUnmarshaller.transform(ENCRYPTED_ASSERTION_BLOB); assertThat(encryptedAssertion).isEqualTo(expected); } |
### Question:
AuthnRequestIssueInstantValidator { public boolean isValid(DateTime issueInstant) { final Duration authnRequestValidityDuration = samlAuthnRequestValidityDurationConfiguration.getAuthnRequestValidityDuration(); return !issueInstant.isBefore(DateTime.now().minus(authnRequestValidityDuration.toMilliseconds())); } @Inject AuthnRequestIssueInstantValidator(SamlAuthnRequestValidityDurationConfiguration samlAuthnRequestValidityDurationConfiguration); boolean isValid(DateTime issueInstant); }### Answer:
@Test public void validate_shouldReturnFalseIfIssueInstantMoreThan5MinutesAgo() { DateTimeFreezer.freezeTime(); DateTime issueInstant = DateTime.now().minusMinutes(AUTHN_REQUEST_VALIDITY_MINS).minusSeconds(1); boolean validity = authnRequestIssueInstantValidator.isValid(issueInstant); assertThat(validity).isEqualTo(false); }
@Test public void validate_shouldReturnTrueIfIssueInstant5MinsAgo() { DateTimeFreezer.freezeTime(); DateTime issueInstant = DateTime.now().minusMinutes(AUTHN_REQUEST_VALIDITY_MINS); boolean validity = authnRequestIssueInstantValidator.isValid(issueInstant); assertThat(validity).isEqualTo(true); }
@Test public void validate_shouldReturnTrueIfIssueInstantLessThan5MinsAgo() { DateTimeFreezer.freezeTime(); DateTime issueInstant = DateTime.now().minusMinutes(AUTHN_REQUEST_VALIDITY_MINS).plusSeconds(1); boolean validity = authnRequestIssueInstantValidator.isValid(issueInstant); assertThat(validity).isEqualTo(true); } |
### Question:
AuthnRequestFromTransactionValidator implements SamlValidator<AuthnRequest> { @Override public void validate(AuthnRequest request) { issuerValidator.validate(request.getIssuer()); validateRequestId(request); validateIssueInstant(request); validateSignaturePresence(request); validateVersion(request); validateNameIdPolicy(request); validateScoping(request); validateProtocolBinding(request); validatePassiveXSBoolean(request); } AuthnRequestFromTransactionValidator(
IssuerValidator issuerValidator,
DuplicateAuthnRequestValidator duplicateAuthnRequestValidator,
AuthnRequestIssueInstantValidator issueInstantValidator); @Override void validate(AuthnRequest request); }### Answer:
@Test public void validate_shouldDoNothingIfIdIsValid() throws Exception { validator.validate(anAuthnRequest().withId("a43qif88dsfv").build()); validator.validate(anAuthnRequest().withId("_443qif88dsfv").build()); }
@Test public void validateRequest_shouldDoNothingIfRequestIsSigned() throws Exception { validator.validate(anAuthnRequest().build()); }
@Test public void validateIssuer_shouldDoNothingIfFormatAttributeIsMissing() throws Exception { validator.validate(anAuthnRequest().withIssuer(anIssuer().withFormat(null).build()).build()); }
@Test public void validateIssuer_shouldDoNothingIfFormatAttributeHasValidValue() throws Exception { validator.validate(anAuthnRequest().withIssuer(anIssuer().withFormat(NameIDType.ENTITY).build()).build()); }
@Test public void validateNameIdPolicy_shouldDoNothingIfNameIdPolicyIsMissing() throws Exception { validator.validate(anAuthnRequest().build()); }
@Test public void validateNameIdPolicy_shouldDoNothingIfNameIdPolicyFormatHasValidValue() throws Exception { validator.validate(anAuthnRequest().withNameIdPolicy(aNameIdPolicy().withFormat(NameIDType.PERSISTENT).build()).build()); }
@Test public void validateProtocolBinding_shouldDoNothingIfProtocolBindingHasValidValue() throws Exception { validator.validate(anAuthnRequest().withProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI).build()); }
@Test(expected = SamlDuplicateRequestIdException.class) public void validateRequest_shouldThrowExceptionIfIsDuplicateRequestIdIsPresent() throws Exception { final String requestId = generateRequestId(); final String oneIssuerId = "some-issuer-id"; final String anotherIssuerId = "some-other-issuer-id"; final AuthnRequest authnRequest = anAuthnRequest().withId(requestId).withIssuer(anIssuer().withIssuerId(oneIssuerId).build()).build(); validator.validate(authnRequest); final AuthnRequest duplicateIdAuthnRequest = anAuthnRequest().withId(requestId).withIssuer(anIssuer().withIssuerId(anotherIssuerId).build()).build(); validateThrows( duplicateIdAuthnRequest, SamlTransformationErrorFactory.duplicateRequestId(requestId, duplicateIdAuthnRequest.getIssuer().getValue()) ); }
@Test public void validate_shouldDoNothingIfVersionNumberIsTwoPointZero() throws Exception { validator.validate(anAuthnRequest().withVersionNumber(SAML_VERSION_NUMBER).build()); } |
### Question:
LevelsOfAssuranceConfigValidator { protected void validateAllTransactionsAreLOA1OrLOA2(Set<TransactionConfig> transactionConfig) { List<TransactionConfig> badTransactionConfigs = transactionConfig.stream() .filter(x -> { List<LevelOfAssurance> levelsOfAssurance = x.getLevelsOfAssurance(); boolean isLoa1 = levelsOfAssurance.equals(asList(LEVEL_1, LEVEL_2)); boolean isLoa2And1 = levelsOfAssurance.equals(asList(LEVEL_2, LEVEL_1)); boolean isLoa2 = levelsOfAssurance.equals(singletonList(LEVEL_2)); return !(isLoa1 || isLoa2 || isLoa2And1); }) .collect(Collectors.toList()); if(!badTransactionConfigs.isEmpty()) { throw ConfigValidationException.createTransactionsRequireUnsupportedLevelOfAssurance(badTransactionConfigs); } } void validateLevelsOfAssurance(final Set<IdentityProviderConfig> identityProviderConfig,
final Set<TransactionConfig> transactionConfig); }### Answer:
@Test public void shouldAllowLOA1TransactionConfiguration() { Set<TransactionConfig> transactionsConfig = Set.of(loa1And2Transaction); try { levelsOfAssuranceConfigValidator.validateAllTransactionsAreLOA1OrLOA2(transactionsConfig); } catch (Exception e) { fail("Expected exception not thrown"); } }
@Test public void shouldAllowLOA2AndLOA1TransactionConfiguration() { Set<TransactionConfig> transactionsConfig = Set.of(loa2And1Transaction); try { levelsOfAssuranceConfigValidator.validateAllTransactionsAreLOA1OrLOA2(transactionsConfig); } catch (Exception e) { fail("Expected exception not thrown"); } }
@Test public void shouldAllowLOA2TransactionConfiguration() { Set<TransactionConfig> transactionsConfig = Set.of(loa2Transaction); try { levelsOfAssuranceConfigValidator.validateAllTransactionsAreLOA1OrLOA2(transactionsConfig); } catch (Exception e) { fail("Expected exception not thrown"); } }
@Test(expected = ConfigValidationException.class) public void shouldThrowWhenTransactionIsLoa1Only() { levelsOfAssuranceConfigValidator.validateAllTransactionsAreLOA1OrLOA2(Set.of(loa1OnlyTransaction)); }
@Test(expected = ConfigValidationException.class) public void shouldThrowWhenTransactionIsNotLoa1OrLoa2() { levelsOfAssuranceConfigValidator.validateAllTransactionsAreLOA1OrLOA2(Set.of(loa3OnlyTransaction)); } |
### Question:
DuplicateAuthnRequestValidator { public boolean valid(String requestId) { AuthnRequestIdKey key = new AuthnRequestIdKey(requestId); if (previousRequests.contains(key) && previousRequests.getExpiration(key).isAfterNow()) { return false; } DateTime expire = DateTime.now().plus(expirationDuration); previousRequests.setExpiration(key, expire); return true; } @Inject DuplicateAuthnRequestValidator(IdExpirationCache<AuthnRequestIdKey> previousRequests, SamlDuplicateRequestValidationConfiguration samlDuplicateRequestValidationConfiguration); boolean valid(String requestId); }### Answer:
@Test public void valid_shouldThrowAnExceptionIfTheAuthnRequestIsADuplicateOfAPreviousOne() throws Exception { final String duplicateRequestId = "duplicate-id"; duplicateAuthnRequestValidator.valid(duplicateRequestId); boolean isValid = duplicateAuthnRequestValidator.valid(duplicateRequestId); assertThat(isValid).isEqualTo(false); }
@Test public void valid_shouldPassIfTheAuthnRequestIsNotADuplicateOfAPreviousOne() throws Exception { duplicateAuthnRequestValidator.valid("some-request-id"); boolean isValid = duplicateAuthnRequestValidator.valid("another-request-id"); assertThat(isValid).isEqualTo(true); }
@Test public void valid_shouldPassIfTwoAuthnRequestsHaveTheSameIdButTheFirstAssertionHasExpired() throws Exception { final String duplicateRequestId = "duplicate-id"; duplicateAuthnRequestValidator.valid(duplicateRequestId); DateTimeFreezer.freezeTime(DateTime.now().plusHours(EXPIRATION_HOURS).plusMinutes(1)); boolean isValid = duplicateAuthnRequestValidator.valid(duplicateRequestId); assertThat(isValid).isEqualTo(true); }
@Test public void valid_shouldFailIfAuthnRequestsReceivedWithSameIdAndFirstIdHasNotExpired() throws Exception { final String duplicateRequestId = "duplicate-id"; duplicateAuthnRequestValidator.valid(duplicateRequestId); DateTimeFreezer.freezeTime(DateTime.now().plusHours(EXPIRATION_HOURS).minusMinutes(1)); boolean isValid = duplicateAuthnRequestValidator.valid(duplicateRequestId); assertThat(isValid).isEqualTo(false); } |
### Question:
EncryptedResponseFromMatchingServiceValidator { public void validate(Response response) { IssuerValidator.validate(response); RequestIdValidator.validate(response); validateResponse(response); } void validate(Response response); }### Answer:
@Test public void validateRequest_shouldDoNothingIfResponseIsSigned() throws Exception { Response response = aResponse().withStatus(happyStatus).build(); validator.validate(response); }
@Test public void validateIssuer_shouldDoNothingIfFormatAttributeIsMissing() throws Exception { Issuer issuer = anIssuer().withFormat(null).build(); Response response = aResponse().withIssuer(issuer).withStatus(happyStatus).build(); validator.validate(response); }
@Test public void validateIssuer_shouldDoNothingIfFormatAttributeHasValidValue() throws Exception { Issuer issuer = anIssuer().withFormat(NameIDType.ENTITY).build(); Response response = aResponse().withIssuer(issuer).withStatus(happyStatus).build(); validator.validate(response); }
@Test public void validate_shouldDoNothingIfAResponderStatusContainsASubStatusOfNoMatch() throws Exception { Status status = createStatus(StatusCode.RESPONDER, createSubStatusCode(SamlStatusCode.NO_MATCH)); Response response = aResponse().withStatus(status).withNoDefaultAssertion().build(); validator.validate(response); }
@Test public void validate_shouldDoNothingIfASuccessStatusContainsASubStatusOfMatch() throws Exception { Response response = aResponse().withStatus(happyStatus).build(); validator.validate(response); }
@Test public void validate_shouldDoNothingIfASuccessStatusContainsASubStatusOfNoMatch() throws Exception { Status status = createStatus(StatusCode.SUCCESS, createSubStatusCode(SamlStatusCode.NO_MATCH)); Response response = aResponse().withStatus(status).build(); validator.validate(response); }
@Test public void validate_shouldDoNothingIfAResponderStatusContainsASubStatusOfMultiMatch() throws Exception { Status status = createStatus(StatusCode.RESPONDER, createSubStatusCode(SamlStatusCode.MULTI_MATCH)); Response response = aResponse().withStatus(status).withNoDefaultAssertion().build(); validator.validate(response); } |
### Question:
ResponseAssertionsFromMatchingServiceValidator { public void validate(ValidatedResponse validatedResponse, ValidatedAssertions validatedAssertions) { if (!validatedResponse.isSuccess()) return; for (Assertion assertion : validatedAssertions.getAssertions()) { assertionValidator.validate(assertion, validatedResponse.getInResponseTo(), hubEntityId); if (assertion.getAuthnStatements().isEmpty()) { throw new SamlValidationException(missingAuthnStatement()); } if (assertion.getAuthnStatements().get(0).getAuthnContext() == null) { throw new SamlValidationException(authnContextMissingError()); } } } ResponseAssertionsFromMatchingServiceValidator(AssertionValidator assertionValidator, String hubEntityId); void validate(ValidatedResponse validatedResponse, ValidatedAssertions validatedAssertions); }### Answer:
@Test public void validate_shouldNotThrowExceptionIfResponseIsANoMatch() throws Exception { String requestId = "some-request-id"; final Response response = aResponse() .withStatus(aStatus().withStatusCode(aStatusCode().withValue(StatusCode.RESPONDER).build()).build()) .withInResponseTo(requestId) .build(); validator.validate(new ValidatedResponse(response), new ValidatedAssertions(singletonList(anAssertion().buildUnencrypted()))); } |
### Question:
HealthCheckResponseFromMatchingServiceValidator { public void validate(Response response) { IssuerValidator.validate(response); RequestIdValidator.validate(response); validateResponse(response); } void validate(Response response); }### Answer:
@Test public void validateResponse_shouldDoNothingIfStatusIsRequesterErrorAndHasNoSubStatus() throws Exception { Response response = aResponse().withNoDefaultAssertion().withStatus( aStatus().withStatusCode( aStatusCode().withValue(StatusCode.REQUESTER).withSubStatusCode(null ).build() ).build() ).build(); validator.validate(response); } |
### Question:
ResponseAssertionsFromIdpValidator { public void validate(ValidatedResponse validatedResponse, ValidatedAssertions validatedAssertions) { validatedAssertions.getAssertions().forEach( assertion -> identityProviderAssertionValidator.validate(assertion, validatedResponse.getInResponseTo(), hubEntityId) ); if (!validatedResponse.isSuccess()) return; Assertion matchingDatasetAssertion = getMatchingDatasetAssertion(validatedAssertions); Assertion authnStatementAssertion = getAuthnStatementAssertion(validatedAssertions); if (authnStatementAssertion.getAuthnStatements().size() > 1) { throw new SamlValidationException(multipleAuthnStatements()); } matchingDatasetAssertionValidator.validate(matchingDatasetAssertion, validatedResponse.getIssuer().getValue()); authnStatementAssertionValidator.validate(authnStatementAssertion); identityProviderAssertionValidator.validateConsistency(authnStatementAssertion, matchingDatasetAssertion); ipAddressValidator.validate(authnStatementAssertion); } ResponseAssertionsFromIdpValidator(IdentityProviderAssertionValidator assertionValidator,
MatchingDatasetAssertionValidator matchingDatasetAssertionValidator,
AuthnStatementAssertionValidator authnStatementAssertionValidator,
IPAddressValidator ipAddressValidator,
String hubEntityId); void validate(ValidatedResponse validatedResponse, ValidatedAssertions validatedAssertions); }### Answer:
@Test public void validate_shouldDelegateAuthnStatementAssertionValidation() throws Exception { Response response = aResponse() .addEncryptedAssertion(anAssertion().addAttributeStatement(aMatchingDatasetAttributeStatement_1_1().build()).build()) .addEncryptedAssertion(anAssertion().build()) .build(); Assertion authNAssertion = anAssertion().buildUnencrypted(); Assertion mdsAssertion = anAssertion().addAttributeStatement(aMatchingDatasetAttributeStatement_1_1().build()).buildUnencrypted(); List<Assertion> assertions = asList(mdsAssertion, authNAssertion); validator.validate(new ValidatedResponse(response), new ValidatedAssertions(assertions)); verify(authnStatementValidator).validate(authNAssertion); }
@Test public void validate_shouldDelegateMatchingDatasetAssertionValidation() throws Exception { Response response = aResponse() .addEncryptedAssertion(anAssertion().addAttributeStatement(aMatchingDatasetAttributeStatement_1_1().build()).build()) .addEncryptedAssertion(anAssertion().build()) .build(); Assertion authNAssertion = anAssertion().buildUnencrypted(); Assertion mdsAssertion = anAssertion().addAttributeStatement(aMatchingDatasetAttributeStatement_1_1().build()).buildUnencrypted(); List<Assertion> assertions = asList(mdsAssertion, authNAssertion); validator.validate(new ValidatedResponse(response), new ValidatedAssertions(assertions)); verify(matchingDatasetAssertionValidator).validate(mdsAssertion, response.getIssuer().getValue()); }
@Test public void validate_shouldDelegateToIpAddressValidator() throws Exception { Assertion authnStatementAssertion = anAssertion().addAuthnStatement(anAuthnStatement().build()).buildUnencrypted(); Response response = aResponse() .addEncryptedAssertion(anAssertion().addAttributeStatement(aMatchingDatasetAttributeStatement_1_1().build()).build()) .addEncryptedAssertion(anAssertion().addAuthnStatement(anAuthnStatement().build()).build()) .build(); List<Assertion> assertions = asList(anAssertion().addAttributeStatement(aMatchingDatasetAttributeStatement_1_1().build()).buildUnencrypted(), authnStatementAssertion); validator.validate(new ValidatedResponse(response), new ValidatedAssertions(assertions)); verify(ipAddressValidator).validate(authnStatementAssertion); } |
### Question:
EncryptedResponseFromIdpValidator { public void validate(Response response) { IssuerValidator.validate(response); RequestIdValidator.validate(response); validateResponse(response); } EncryptedResponseFromIdpValidator(final SamlStatusToAuthenticationStatusCodeMapper<T> statusCodeMapper); void validate(Response response); }### Answer:
@Test public void validateRequest_shouldNotErrorIfRequestIsSigned() throws Exception { Response response = getResponseBuilderWithTwoAssertions().build(); validator.validate(response); }
@Test public void validateIssuer_shouldNotErrorIfFormatAttributeIsMissing() throws Exception { Issuer issuer = anIssuer().withFormat(null).build(); Response response = getResponseBuilderWithTwoAssertions().withIssuer(issuer).build(); validator.validate(response); }
@Test public void validateIssuer_shouldNotErrorIfFormatAttributeHasValidValue() throws Exception { Issuer issuer = anIssuer().withFormat(NameIDType.ENTITY).build(); Response response = getResponseBuilderWithTwoAssertions().withIssuer(issuer).build(); validator.validate(response); }
@Test public void validateStatus_shouldNotErrorIfStatusIsResponderWithSubStatusAuthnFailed() throws Exception { Status status = createStatus(StatusCode.RESPONDER, createSubStatusCode(StatusCode.AUTHN_FAILED)); Response response = aResponse().withStatus(status).withNoDefaultAssertion().build(); validator.validate(response); }
@Test public void validateStatus_shouldNotErrorIfStatusIsResponderWithSubStatusNoAuthnContext() throws Exception { Status status = createStatus(StatusCode.RESPONDER, createSubStatusCode(StatusCode.NO_AUTHN_CONTEXT)); Response response = aResponse().withStatus(status).withNoDefaultAssertion().build(); validator.validate(response); }
@Test public void validateStatus_shouldNotErrorIfStatusIsRequesterWithNoSubStatus() throws Exception { Status status = createStatus(StatusCode.REQUESTER); Response response = aResponse().withStatus(status).withNoDefaultAssertion().build(); validator.validate(response); }
@Test public void validateStatus_shouldNotErrorIfStatusIsSuccessWithNoSubStatus() throws Exception { Status status = createStatus(StatusCode.SUCCESS); Response response = getResponseBuilderWithTwoAssertions().withStatus(status).build(); validator.validate(response); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.