Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle complex JSON payloads for Call Choreo function and call Analytics function #187

Merged
merged 11 commits into from
Aug 27, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@
org.wso2.carbon.user.core.service; version="${carbon.kernel.package.import.version.range}",
org.wso2.carbon.identity.conditional.auth.functions.common.utils,
org.wso2.carbon.identity.conditional.auth.functions.common.auth,
org.wso2.carbon.identity.conditional.auth.functions.common.model,
javax.net.ssl,
org.apache.http.impl.conn,
org.osgi.framework,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@

import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.HttpHeaders.CONTENT_TYPE;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.CommonUtils.getPayloadDataMap;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.Constants.OUTCOME_FAIL;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.Constants.OUTCOME_SUCCESS;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.Constants.OUTCOME_TIMEOUT;
Expand All @@ -73,7 +74,7 @@ public void callAnalytics(Map<String, String> metadata,
* Eg: Polyglot Map (Map implementation from GraalJS) will be unavailable when the Polyglot Context is closed.
*/
Map<String, String> metadataMap = new HashMap<>(metadata);
Map<String, Object> payloadDataMap = new HashMap<>(payloadData);
Map<String, Object> payloadDataMap = getPayloadDataMap(payloadData);
AsyncProcess asyncProcess = new AsyncProcess((authenticationContext, asyncReturn) -> {

String appName = metadataMap.get(PARAM_APP_NAME);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,25 @@

package org.wso2.carbon.identity.conditional.auth.functions.analytics;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.graalvm.polyglot.HostAccess;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsParameters;
import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext;
import org.wso2.carbon.identity.application.authentication.framework.dao.impl.CacheBackedLongWaitStatusDAO;
import org.wso2.carbon.identity.application.authentication.framework.dao.impl.LongWaitStatusDAOImpl;
import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder;
import org.wso2.carbon.identity.application.authentication.framework.store.LongWaitStatusStoreService;
import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.common.model.script.AuthenticationScriptConfig;
import org.wso2.carbon.identity.common.testng.InjectMicroservicePort;
import org.wso2.carbon.identity.common.testng.WithCarbonHome;
import org.wso2.carbon.identity.common.testng.WithH2Database;
Expand All @@ -38,6 +45,7 @@
import org.wso2.carbon.identity.conditional.auth.functions.common.internal.FunctionsDataHolder;
import org.wso2.carbon.identity.conditional.auth.functions.test.utils.sequence.JsSequenceHandlerAbstractTest;
import org.wso2.carbon.identity.conditional.auth.functions.test.utils.sequence.JsTestException;
import org.wso2.carbon.identity.conditional.auth.functions.test.utils.sequence.ResponseValidator;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.governance.IdentityGovernanceException;
import org.wso2.carbon.identity.governance.IdentityGovernanceService;
Expand All @@ -47,13 +55,15 @@
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
Expand All @@ -65,6 +75,11 @@
@Path("/")
public class CallAnalyticsFunctionImplTest extends JsSequenceHandlerAbstractTest {

public static final String ANALYTICS_SERVICE_CHECK_PAYLOAD = "/analytics-service-check-payload";
public static final String ANALYTICS_PAYLOAD_JSON = "analytics-payload.json";
public static final String ANALYTICS_PAYLOAD_TEST_SP = "analytics-payload-test-sp.xml";
public static final String ANALYTICS_PAYLOAD = "analytics-payload.json";

@WithRealmService
private RealmService realmService;

Expand Down Expand Up @@ -126,6 +141,79 @@ public void testRiskScore() throws JsTestException, NoSuchFieldException,
assertEquals(context.getSelectedAcr(), "1", "Expected acr value not found");
}

@DataProvider(name = "payloadType")
public Object[][] getCookieValues() {

return new Object[][]{
{"serializedComprehensivePayload"},
{"nonSerializedComprehensivePayload"}
};
}

@Test(dataProvider = "payloadType")
public void testAnalyticsPayload(String payloadType)
throws JsTestException, IdentityGovernanceException, NoSuchFieldException, IllegalAccessException {

sequenceHandlerRunner.registerJsFunction("validateResponse", new ResponseValidatorImpl());
IdentityGovernanceService identityGovernanceService = Mockito.mock(IdentityGovernanceService.class);
FunctionsDataHolder functionsDataHolder = Mockito.mock(FunctionsDataHolder.class);
Mockito.when(functionsDataHolder.getIdentityGovernanceService()).thenReturn(identityGovernanceService);
Property property = new Property();
property.setValue("http://localhost:" + microServicePort);
Mockito.when(identityGovernanceService.getConfiguration(new String[]{AnalyticsEngineConfigImpl.RECEIVER},
"test_domain")).thenReturn(new Property[]{property});

Field functionsDataHolderInstance = FunctionsDataHolder.class.getDeclaredField("instance");
functionsDataHolderInstance.setAccessible(true);
functionsDataHolderInstance.set(null, functionsDataHolder);

Field frameworkServiceDataHolderInstance = FrameworkServiceDataHolder.class.getDeclaredField("instance");
frameworkServiceDataHolderInstance.setAccessible(true);
FrameworkServiceDataHolder availableInstance = (FrameworkServiceDataHolder)frameworkServiceDataHolderInstance.get(null);

LongWaitStatusDAOImpl daoImpl = new LongWaitStatusDAOImpl();
CacheBackedLongWaitStatusDAO cacheBackedDao = new CacheBackedLongWaitStatusDAO(daoImpl);
int connectionTimeout = 5000;
LongWaitStatusStoreService longWaitStatusStoreService =
new LongWaitStatusStoreService(cacheBackedDao, connectionTimeout);
availableInstance.setLongWaitStatusStoreService(longWaitStatusStoreService);

AuthenticationContext context = getAuthenticationContextForPayloadTest(payloadType);

HttpServletRequest req = sequenceHandlerRunner.createHttpServletRequest();
HttpServletResponse resp = sequenceHandlerRunner.createHttpServletResponse();

sequenceHandlerRunner.handle(req, resp, context, "carbon.super");

assertNotNull(context.getSelectedAcr());
assertEquals(context.getSelectedAcr(), "1", "Expected acr value not found");

}

private AuthenticationContext getAuthenticationContextForPayloadTest(String payloadType)
throws JsTestException {

ServiceProvider sp1 = sequenceHandlerRunner.loadServiceProviderFromResource(ANALYTICS_PAYLOAD_TEST_SP, this);
LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig =
sp1.getLocalAndOutBoundAuthenticationConfig();
AuthenticationScriptConfig authenticationScriptConfig = localAndOutboundAuthenticationConfig
.getAuthenticationScriptConfig();

String jsonPayload = sequenceHandlerRunner.loadJson(ANALYTICS_PAYLOAD, this).toString();
String content = authenticationScriptConfig.getContent();
String newContent =
String.format(content, jsonPayload, jsonPayload, ANALYTICS_SERVICE_CHECK_PAYLOAD, payloadType);
authenticationScriptConfig.setContent(newContent);
localAndOutboundAuthenticationConfig.setAuthenticationScriptConfig(authenticationScriptConfig);
sp1.setLocalAndOutBoundAuthenticationConfig(localAndOutboundAuthenticationConfig);

AuthenticationContext context = sequenceHandlerRunner.createAuthenticationContext(sp1);
SequenceConfig sequenceConfig = sequenceHandlerRunner.getSequenceConfig(context, sp1);
context.setSequenceConfig(sequenceConfig);
context.initializeAnalyticsData();
return context;
}

@POST
@Path("/{appName}/{inputStream}")
@Consumes("application/json")
Expand All @@ -143,4 +231,54 @@ public Map<String, Map<String, String>> analyticsReceiver(@PathParam("appName")
response.put("event", responseEvent);
return response;
}

@POST
@Path(ANALYTICS_SERVICE_CHECK_PAYLOAD)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> analyticsReceiverCheckPayload(Map<String, Object> data) throws JsTestException {

JsonObject expectedPayload = sequenceHandlerRunner.loadJson(ANALYTICS_PAYLOAD_JSON, this);
Gson gson = new Gson();
String dataStr = gson.toJson(data.get("event"));
JsonObject actualPayload = gson.fromJson(dataStr, JsonObject.class);

if (expectedPayload.equals(actualPayload)) {
Map<String, String> responseEvent = new HashMap<>();
responseEvent.put("riskScore", "1");
Map<String, Object> response = new HashMap<>();
response.put("event", responseEvent);
response.put("payload", actualPayload);
return response;
} else {
throw new JsTestException("Payloads do not match. " +
String.format("Expected payload: %s, Actual payload: %s", expectedPayload, actualPayload));
}
}

/**
* Response validator implementation.
*/
public class ResponseValidatorImpl implements ResponseValidator {

/**
* Validate the response.
*
* @param response JSON Response from the analytics engine.
* @return True if the response matches the expected JSON response.
*/
@Override
@HostAccess.Export
public boolean validateResponse(JsParameters response) throws JsTestException {

if (response != null) {
JsonObject expectedResponse = sequenceHandlerRunner.loadJson(ANALYTICS_PAYLOAD_JSON, this);
Gson gson = new Gson();
String dataStr = gson.toJson(response.getWrapped());
JsonObject actualResponse = gson.fromJson(dataStr, JsonObject.class);
return actualResponse.equals(expectedResponse);
}
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<!--
~ Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 LLC. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<ServiceProvider>
<ApplicationID>1</ApplicationID>
<ApplicationName>default</ApplicationName>
<Description>Default Service Provider</Description>
<InboundAuthenticationConfig>
<InboundAuthenticationRequestConfigs>
<InboundAuthenticationRequestConfig>
<InboundAuthKey>default</InboundAuthKey>
<InboundAuthType></InboundAuthType>
<Properties></Properties>
</InboundAuthenticationRequestConfig>
</InboundAuthenticationRequestConfigs>
</InboundAuthenticationConfig>
<LocalAndOutBoundAuthenticationConfig>
<AuthenticationSteps>
<AuthenticationStep>
<StepOrder>1</StepOrder>
<LocalAuthenticatorConfigs>
<LocalAuthenticatorConfig>
<Name>BasicMockAuthenticator</Name>
<DisplayName>basicauth</DisplayName>
<IsEnabled>true</IsEnabled>
</LocalAuthenticatorConfig>
</LocalAuthenticatorConfigs>
<SubjectStep>true</SubjectStep>
<AttributeStep>true</AttributeStep>
</AuthenticationStep>
<AuthenticationStep>
<StepOrder>2</StepOrder>
<FederatedIdentityProviders>
<IdentityProvider>
<IdentityProviderName>HwkMockAuthenticator</IdentityProviderName>
<IsEnabled>true</IsEnabled>
<DefaultAuthenticatorConfig>HwkMockAuthenticator</DefaultAuthenticatorConfig>
<FederatedAuthenticatorConfigs>
<FederatedAuthenticatorConfig>
<Name>HwkMockAuthenticator</Name>
<IsEnabled>true</IsEnabled>
</FederatedAuthenticatorConfig>
</FederatedAuthenticatorConfigs>
</IdentityProvider>
</FederatedIdentityProviders>
<SubjectStep>false</SubjectStep>
<AttributeStep>false</AttributeStep>
</AuthenticationStep>
<AuthenticationStep>
<StepOrder>3</StepOrder>
<FederatedIdentityProviders>
<IdentityProvider>
<IdentityProviderName>FptMockAuthenticator</IdentityProviderName>
<IsEnabled>true</IsEnabled>
<DefaultAuthenticatorConfig>FptMockAuthenticator</DefaultAuthenticatorConfig>
<FederatedAuthenticatorConfigs>
<FederatedAuthenticatorConfig>
<Name>FptMockAuthenticator</Name>
<IsEnabled>true</IsEnabled>
</FederatedAuthenticatorConfig>
</FederatedAuthenticatorConfigs>
</IdentityProvider>
</FederatedIdentityProviders>
<SubjectStep>false</SubjectStep>
<AttributeStep>false</AttributeStep>
</AuthenticationStep>
<AuthenticationStep>
<StepOrder>4</StepOrder>
<LocalAuthenticatorConfigs>
<LocalAuthenticatorConfig>
<Name>MockFallbackAuthenticator</Name>
<DisplayName>basicauthfallback</DisplayName>
<IsEnabled>true</IsEnabled>
</LocalAuthenticatorConfig>
</LocalAuthenticatorConfigs>
<SubjectStep>true</SubjectStep>
<AttributeStep>true</AttributeStep>
</AuthenticationStep>
</AuthenticationSteps>
<AuthenticationScript type="application/javascript" enabled="true"><![CDATA[
var serializedComprehensivePayload = %s;
function onLoginRequest(context) {
executeStep(1, {
onSuccess: function (context) {
var nonSerializedComprehensivePayload = %s;
var username = context.steps[1].subject.username;
callAnalytics({'ReceiverUrl': '%s'}, %s, {
onSuccess: function (context, data) {
if (data.event.riskScore > 0 && validateResponse(data.payload)) {
Log.info('data.event.riskScore > 0');
context.selectedAcr = ''+ data.event.riskScore;
}
}, onFail: function (context, data) {
Log.info('fail Called');
}
});
}
});
}

]]></AuthenticationScript>
<AuthenticationType>flow</AuthenticationType>
</LocalAndOutBoundAuthenticationConfig>
<RequestPathAuthenticatorConfigs></RequestPathAuthenticatorConfigs>
<InboundProvisioningConfig></InboundProvisioningConfig>
<OutboundProvisioningConfig></OutboundProvisioningConfig>
<ClaimConfig>
<AlwaysSendMappedLocalSubjectId>true</AlwaysSendMappedLocalSubjectId>
</ClaimConfig>
<PermissionAndRoleConfig></PermissionAndRoleConfig>
</ServiceProvider>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"stringKey": "stringValue",
"numberKey": 123,
"booleanKey": true,
"arrayKey": [
"arrayString",
456,
false,
{
"nestedObjectInArrayKey": "nestedObjectValue",
"nestedArrayInArrayKey": ["nestedArrayValue1", "nestedArrayValue2"]
}
],
"objectKey": {
"objectStringKey": "objectStringValue",
"objectNumberKey": 789,
"objectBooleanKey": false,
"nestedObjectKey": {
"nestedObjectStringKey": "nestedObjectStringValue",
"nestedObjectArrayKey": [
"nestedArrayValue1",
101112,
true
]
},
"arrayOfObjectsKey": [
{
"arrayOfObjectsStringKey": "arrayOfObjectsStringValue1",
"arrayOfObjectsNumberKey": 131415,
"arrayOfObjectsBooleanKey": true
},
{
"arrayOfObjectsStringKey": "arrayOfObjectsStringValue2",
"arrayOfObjectsNumberKey": 161718,
"arrayOfObjectsBooleanKey": false
}
]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@
org.wso2.carbon.user.core.service; version="${carbon.kernel.package.import.version.range}",
org.wso2.carbon.identity.conditional.auth.functions.common.utils,
org.wso2.carbon.identity.conditional.auth.functions.common.auth,
org.wso2.carbon.identity.conditional.auth.functions.common.model,
javax.net.ssl,
org.apache.http.impl.conn,
org.osgi.framework,
Expand Down
Loading
Loading