Search in sources :

Example 11 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project carbon-identity-framework by wso2.

the class LoggerUtils method triggerDiagnosticLogEvent.

/**
 * Trigger Diagnostic Log Event.
 *
 * @param componentId       Component ID.
 * @param input             Input parameters.
 * @param resultStatus      Result status.
 * @param resultMessage     Result message.
 * @param actionId          Action ID.
 * @param configurations    System/application level configurations.
 */
public static void triggerDiagnosticLogEvent(String componentId, Map<String, Object> input, String resultStatus, String resultMessage, String actionId, Map<String, Object> configurations) {
    try {
        Map<String, Object> diagnosticLogProperties = new HashMap<>();
        String id = UUID.randomUUID().toString();
        Instant recordedAt = parseDateTime(Instant.now().toString());
        String requestId = MDC.get(CORRELATION_ID_MDC);
        String flowId = MDC.get(FLOW_ID_MDC);
        DiagnosticLog diagnosticLog = new DiagnosticLog(id, recordedAt, requestId, flowId, resultStatus, resultMessage, actionId, componentId, input, configurations);
        IdentityEventService eventMgtService = CentralLogMgtServiceComponentHolder.getInstance().getIdentityEventService();
        diagnosticLogProperties.put(CarbonConstants.LogEventConstants.DIAGNOSTIC_LOG, diagnosticLog);
        int tenantId = IdentityTenantUtil.getTenantId(CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
        diagnosticLogProperties.put(CarbonConstants.LogEventConstants.TENANT_ID, tenantId);
        Event diagnosticLogEvent = new Event(PUBLISH_DIAGNOSTIC_LOG, diagnosticLogProperties);
        eventMgtService.handleEvent(diagnosticLogEvent);
    } catch (IdentityEventException e) {
        String errorLog = "Error occurred when firing the diagnostic log event.";
        log.error(errorLog, e);
    }
}
Also used : DiagnosticLog(org.wso2.carbon.utils.DiagnosticLog) HashMap(java.util.HashMap) IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) Instant(java.time.Instant) Event(org.wso2.carbon.identity.event.event.Event) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService)

Example 12 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project carbon-identity-framework by wso2.

the class ClaimMetadataEventPublisherProxy method doPublishEvent.

private void doPublishEvent(Event event) {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Event: " + event.getEventName() + " is published for the claim management operation in " + "the tenant with the tenantId: " + event.getEventProperties().get(IdentityEventConstants.EventProperty.TENANT_ID));
        }
        IdentityEventService eventService = IdentityClaimManagementServiceDataHolder.getInstance().getIdentityEventService();
        eventService.handleEvent(event);
    } catch (IdentityEventException e) {
        log.error("Error while publishing the event: " + event.getEventName() + ".", e);
    }
}
Also used : IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService)

Example 13 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project carbon-identity-framework by wso2.

the class IdentityEventServiceDataHolderTest method getEventMgtService.

@Test
public void getEventMgtService() {
    IdentityEventServiceDataHolder identityEventServiceDataHolder = IdentityEventServiceDataHolder.getInstance();
    identityEventServiceDataHolder.setEventMgtService(identityEventService);
    Assert.assertEquals(identityEventServiceDataHolder.getEventMgtService(), identityEventService);
}
Also used : IdentityEventServiceDataHolder(org.wso2.carbon.identity.event.internal.IdentityEventServiceDataHolder) Test(org.testng.annotations.Test)

Example 14 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project carbon-identity-framework by wso2.

the class IdentityEventServiceImplTest method testHandleEvent.

@Test
public void testHandleEvent() throws IdentityEventException {
    Event event = new Event("eventName");
    event.addEventProperty("value", "value");
    abstractEventHandler = mock(AbstractEventHandler.class);
    doReturn(true).when(abstractEventHandler).canHandle(any(MessageContext.class));
    doReturn(true).when(abstractEventHandler).isAssociationAsync(anyString());
    List list = new ArrayList();
    list.add(abstractEventHandler);
    IdentityEventServiceComponent.eventHandlerList = list;
    List abstractEventHandlerList = new ArrayList();
    abstractEventHandlerList.add(abstractEventHandler);
    IdentityEventService identityEventService = new IdentityEventServiceImpl(abstractEventHandlerList, 1);
    identityEventService.handleEvent(event);
    Mockito.verify(abstractEventHandler).canHandle(any(MessageContext.class));
}
Also used : AbstractEventHandler(org.wso2.carbon.identity.event.handler.AbstractEventHandler) ArrayList(java.util.ArrayList) Event(org.wso2.carbon.identity.event.event.Event) ArrayList(java.util.ArrayList) List(java.util.List) MessageContext(org.wso2.carbon.identity.core.bean.context.MessageContext) Test(org.testng.annotations.Test) IdentityBaseTest(org.wso2.carbon.identity.testutil.IdentityBaseTest)

Example 15 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest.

/**
 * Tests the scenario of authorization request from the client
 */
@Test(dataProvider = "provideAuthzRequestData", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest(String clientId, String redirectUri, String pkceChallengeCode, String pkceChallengeMethod, String prompt, boolean clientValid, boolean pkceEnabled, boolean supportPlainPkce, String expectedLocation) throws Exception {
    Map<String, String[]> requestParams = new HashMap();
    Map<String, Object> requestAttributes = new HashMap();
    requestParams.put(CLIENT_ID, new String[] { clientId });
    // No consent data is saved in the cache yet and client doesn't send cache key
    requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { null });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE, new String[] { pkceChallengeCode });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE_METHOD, new String[] { pkceChallengeMethod });
    requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
    if (redirectUri != null) {
        requestParams.put("acr_values", new String[] { redirectUri });
        requestParams.put("claims", new String[] { "essentialClaims" });
        requestParams.put(MultitenantConstants.TENANT_DOMAIN, new String[] { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME });
    }
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    // No authentication data is saved in the cache yet and client doesn't send cache key
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, null);
    if (prompt != null) {
        requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { prompt });
    }
    boolean checkErrorCode = ERROR_PAGE_URL.equals(expectedLocation);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    mockOAuthServerConfiguration();
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
    responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
    responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
    when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);
    spy(FrameworkUtils.class);
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockEndpointUtil(false);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    when(oAuth2Service.isPKCESupportEnabled()).thenReturn(pkceEnabled);
    if (ERROR_PAGE_URL.equals(expectedLocation) && OAuthConstants.Prompt.NONE.equals(prompt)) {
        doThrow(new IdentityOAuth2Exception("error")).when(EndpointUtil.class, "getLoginPageURL", anyString(), anyString(), anyBoolean(), anyBoolean(), anySet(), anyMap(), any());
        checkErrorCode = false;
    }
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
    validationResponseDTO.setValidClient(clientValid);
    validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
    if (!clientValid) {
        validationResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        validationResponseDTO.setErrorMsg("client is invalid");
    }
    validationResponseDTO.setPkceMandatory(supportPlainPkce);
    validationResponseDTO.setPkceSupportPlain(supportPlainPkce);
    when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
    if (StringUtils.equals(expectedLocation, LOGIN_PAGE_URL) || StringUtils.equals(expectedLocation, ERROR_PAGE_URL)) {
        CommonAuthenticationHandler handler = mock(CommonAuthenticationHandler.class);
        doAnswer(invocation -> {
            CommonAuthRequestWrapper request = (CommonAuthRequestWrapper) invocation.getArguments()[0];
            request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
            CommonAuthResponseWrapper wrapper = (CommonAuthResponseWrapper) invocation.getArguments()[1];
            wrapper.sendRedirect(expectedLocation);
            return null;
        }).when(handler).doGet(any(), any());
        whenNew(CommonAuthenticationHandler.class).withNoArguments().thenReturn(handler);
    }
    mockServiceURLBuilder();
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response);
    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");
    MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
    assertNotNull(responseMetadata, "Response metadata is null");
    assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
    String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
    assertTrue(location.contains(expectedLocation), "Unexpected redirect url in the response");
    if (checkErrorCode) {
        assertTrue(location.contains(OAuth2ErrorCodes.INVALID_REQUEST), "Expected error code not found in URL");
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) Matchers.anyString(org.mockito.Matchers.anyString) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

IdentityEventService (org.wso2.carbon.identity.event.services.IdentityEventService)18 HashMap (java.util.HashMap)13 Test (org.testng.annotations.Test)10 IdentityEventException (org.wso2.carbon.identity.event.IdentityEventException)10 Event (org.wso2.carbon.identity.event.event.Event)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 BeforeTest (org.testng.annotations.BeforeTest)8 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 Matchers.anyString (org.mockito.Matchers.anyString)5 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)4 AfterTest (org.testng.annotations.AfterTest)4 OAuthServerConfiguration (org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration)3 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)3 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)3 Method (java.lang.reflect.Method)2 Instant (java.time.Instant)2 Hashtable (java.util.Hashtable)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpMethod (javax.ws.rs.HttpMethod)2