Skip to content

Commit

Permalink
Merge pull request #162 from Sachin-Mamoru/http-get-post-unit-test
Browse files Browse the repository at this point in the history
Added unit tests related to enhanced httpGet and httpPost functions
  • Loading branch information
Sachin-Mamoru authored May 28, 2024
2 parents dd1caae + 89fe864 commit df48abd
Show file tree
Hide file tree
Showing 11 changed files with 971 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
</dependency>

<dependency>
<groupId>org.wso2.carbon.identity.framework</groupId>
Expand Down Expand Up @@ -103,10 +107,6 @@
<artifactId>msf4j-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.orbit.com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.identity.central.log.mgt</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@

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

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
Expand All @@ -42,14 +52,19 @@
import org.wso2.carbon.identity.conditional.auth.functions.test.utils.sequence.JsTestException;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;

import java.util.Date;
import java.time.Instant;
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.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;

import static org.mockito.Matchers.any;
Expand All @@ -67,13 +82,20 @@ public class HTTPGetFunctionImplTest extends JsSequenceHandlerAbstractTest {

private static final String TEST_SP_CONFIG = "http-get-test-sp.xml";
private static final String TEST_HEADERS = "http-get-test-headers.xml";
private static final String TEST_AUTH_CONFIG = "http-get-test-auth-config.xml";
private static final String TEST_AUTH_CONFIG_WITH_BASICAUTH = "http-get-test-auth-config-with-basicauth.xml";
private static final String TEST_AUTH_CONFIG_WITH_APIKEY = "http-get-test-auth-config-with-apikey.xml";
private static final String TEST_AUTH_CONFIG_WITH_BEARERTOKEN = "http-get-test-auth-config-with-bearertoken.xml";
private static final String TEST_AUTH_CONFIG_WITH_CLIENTCREDENTIAL = "http-get-test-auth-config-with" +
"-clientcredential.xml";
private static final String TENANT_DOMAIN = "carbon.super";
private static final String STATUS = "status";
private static final String SUCCESS = "SUCCESS";
private static final String FAILED = "FAILED";
private static final String TOKEN_ENDPOINT_SUCCESS = "success";
private static final String TOKEN_ENDPOINT_FAILURE = "failure";
private static final String ALLOWED_DOMAIN = "abc";
private static final String AUTHORIZATION = "Authorization";
private static final String API_KEY_HEADER = "X-API-KEY";
private HTTPGetFunctionImpl httpGetFunction;

@InjectMicroservicePort
Expand Down Expand Up @@ -113,8 +135,7 @@ protected void tearDownMethod() {
@Test
public void testHttpGetMethod() throws JsTestException {

String requestUrl = getRequestUrl("dummy-get");
String result = executeHttpGetFunction(requestUrl, TEST_SP_CONFIG);
String result = executeHttpGetFunction("dummy-get", TEST_SP_CONFIG);

assertEquals(result, SUCCESS, "The http get request was not successful. Result from request: " + result);
}
Expand All @@ -124,41 +145,88 @@ public void testHttpGetMethodUrlValidation() throws JsTestException, NoSuchField

sequenceHandlerRunner.registerJsFunction("httpGet", new HTTPGetFunctionImpl());
setAllowedDomain(ALLOWED_DOMAIN);
String requestUrl = getRequestUrl("dummy-get");
String result = executeHttpGetFunction(requestUrl, TEST_SP_CONFIG);
String result = executeHttpGetFunction("dummy-get", TEST_SP_CONFIG);

assertEquals(result, FAILED, "The http get request should fail but it was successful. Result from request: "
+ result);
}

/**
* Test http get method with headers.
* Test httpGet method with headers.
* Check if the headers are sent with the request.
*
* @throws JsTestException
*/
@Test
public void testHttpGetMethodWithHeaders() throws JsTestException {

String requestUrl = getRequestUrl("dummy-get-with-headers");
String result = executeHttpGetFunction(requestUrl, TEST_HEADERS);
String result = executeHttpGetFunction("dummy-get-with-headers", TEST_HEADERS);

assertEquals(result, SUCCESS, "The http get request was not successful. Result from request: " + result);
}

/**
* Test http get method with auth config.
* Test httpGet method with basicauth auth config.
* Check if the auth config is applied to the request.
*
* @throws JsTestException
*/
@Test
public void testHttpGetMethodWithAuthConfig() throws JsTestException {
public void testHttpGetMethodWithBasicAuthAuthConfig() throws JsTestException {

String requestUrl = getRequestUrl("dummy-get-with-auth-config");
String result = executeHttpGetFunction(requestUrl, TEST_AUTH_CONFIG);
String result = executeHttpGetFunction("dummy-get-with-basicauth-auth-config", TEST_AUTH_CONFIG_WITH_BASICAUTH);

assertEquals(result, SUCCESS, "The http get request was not successful. Result from request: " + result);
assertEquals(result, SUCCESS,
"The http get request was not successful with basicauth auth config. Result from request: " +
result);
}

/**
* Test httpGet method with apikey auth config.
* Check if the auth config is applied to the request.
*
* @throws JsTestException
*/
@Test
public void testHttpGetMethodWithApiKeyAuthAuthConfig() throws JsTestException {

String result = executeHttpGetFunction("dummy-get-with-apikey-auth-config", TEST_AUTH_CONFIG_WITH_APIKEY);

assertEquals(result, SUCCESS,
"The http get request was not successful with apikey auth config. Result from request: " +
result);
}

/**
* Test httpGet method with bearertoken auth config.
* Check if the auth config is applied to the request.
*
* @throws JsTestException
*/
@Test
public void testHttpGetMethodWithBearerTokenAuthConfig() throws JsTestException {

String result = executeHttpGetFunction("dummy-get-with-bearertoken-auth-config", TEST_AUTH_CONFIG_WITH_BEARERTOKEN);

assertEquals(result, SUCCESS,
"The http get request was not successful with bearertoken auth config. Result from request: " +
result);
}

/**
* Test httpGet method with clientcredential auth config.
* Check if the auth config is applied to the request.
*
* @throws JsTestException
*/
@Test
public void testHttpGetMethodWithClientCredentialAuthConfig() throws JsTestException {

String result = executeHttpGetFunction("dummy-get-with-clientcredential-auth-config", TEST_AUTH_CONFIG_WITH_CLIENTCREDENTIAL);

assertEquals(result, SUCCESS,
"The http get request was not successful with clientcredential auth config. Result from request: " +
result);
}

/**
Expand Down Expand Up @@ -199,10 +267,10 @@ private String getRequestUrl(String path) {
return "http://localhost:" + microServicePort + "/" + path;
}

private String executeHttpGetFunction(String requestUrl, String adaptiveAuthScript) throws JsTestException {
private String executeHttpGetFunction(String path, String adaptiveAuthScript) throws JsTestException {

ServiceProvider sp = sequenceHandlerRunner.loadServiceProviderFromResource(adaptiveAuthScript, this);
updateSPAuthScriptRequestUrl(sp, requestUrl);
updateSPAuthScriptRequestUrl(sp, path);

AuthenticationContext context = sequenceHandlerRunner.createAuthenticationContext(sp);
SequenceConfig sequenceConfig = sequenceHandlerRunner.getSequenceConfig(context, sp);
Expand All @@ -219,18 +287,64 @@ private String executeHttpGetFunction(String requestUrl, String adaptiveAuthScri
return context.getSelectedAcr();
}

private void updateSPAuthScriptRequestUrl(ServiceProvider sp, String url) {
private void updateSPAuthScriptRequestUrl(ServiceProvider sp, String path) {

LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig =
sp.getLocalAndOutBoundAuthenticationConfig();
AuthenticationScriptConfig authenticationScriptConfig = localAndOutboundAuthenticationConfig
.getAuthenticationScriptConfig();
String script = authenticationScriptConfig.getContent();
authenticationScriptConfig.setContent(String.format(script, url));
authenticationScriptConfig.setContent(getFormattedScript(script, path));
localAndOutboundAuthenticationConfig.setAuthenticationScriptConfig(authenticationScriptConfig);
sp.setLocalAndOutBoundAuthenticationConfig(localAndOutboundAuthenticationConfig);
}

private String getFormattedScript(String script, String path) {
switch (path) {
case "dummy-get":
return String.format(script, getRequestUrl("dummy-get"));
case "dummy-get-with-headers":
return String.format(script, getRequestUrl("dummy-get-with-headers"));
case "dummy-get-with-basicauth-auth-config":
return String.format(script, getRequestUrl("dummy-get-with-basicauth-auth-config"));
case "dummy-get-with-apikey-auth-config":
return String.format(script, getRequestUrl("dummy-get-with-apikey-auth-config"));
case "dummy-get-with-bearertoken-auth-config":
return String.format(script, getRequestUrl("dummy-get-with-bearertoken-auth-config"));
case "dummy-get-with-clientcredential-auth-config":
return String.format(script, getRequestUrl("dummy-get-with-clientcredential-auth-config"),
getRequestUrl("dummy-token-endpoint"));
default:
return null;
}
}

/**
* Generates a JSON Web Token for testing purposes.
*/
private String generateTestAccessToken() throws JOSEException {

Instant instant = Instant.now().plusSeconds(3600);
RSAKey senderJWK = new RSAKeyGenerator(2048)
.keyID("123")
.keyUse(KeyUse.SIGNATURE)
.generate();
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
.type(JOSEObjectType.JWT)
.keyID("MWQ5NWUwYWZiMmMzZTIzMzdmMzBhMWM4YjQyMjVhNWM4NjhkMGRmNzFlMGI3ZDlmYmQzNmEyMzhhYjBiNmZhYw_RS256")
.build();
JWTClaimsSet payload = new JWTClaimsSet.Builder()
.issuer("https://test/oauth2/token")
.audience("3ENOyHzZtwaP54apEjuV5H31Q_gb")
.subject("0aac3d44-b5tf-4641-8902-7af8713364f8")
.expirationTime(Date.from(instant))
.build();

SignedJWT signedJWT = new SignedJWT(header, payload);
signedJWT.sign(new RSASSASigner(senderJWK));
return signedJWT.serialize();
}

@GET
@Path("/dummy-get")
@Produces("application/json")
Expand All @@ -256,17 +370,16 @@ public Map<String, String> dummyGetWithHeaders(@HeaderParam(AUTHORIZATION) Strin
}

/**
* Dummy endpoint to test the http get function with auth config.
* Dummy endpoint to test the http get function with basicauth auth config.
*
* @param authorization Authorization header value.
* @return Response.
*/
@GET
@Path("/dummy-get-with-auth-config")
@Path("/dummy-get-with-basicauth-auth-config")
@Produces("application/json")
public Map<String, String> dummyGetWithAuthConfig(@HeaderParam(AUTHORIZATION) String authorization) {
public Map<String, String> dummyGetWithBasicAuthAuthConfig(@HeaderParam(AUTHORIZATION) String authorization) {

System.out.println("Authorization123: " + authorization);
Map<String, String> response = new HashMap<>();
if (authorization != null) {
response.put(STATUS, SUCCESS);
Expand All @@ -275,4 +388,90 @@ public Map<String, String> dummyGetWithAuthConfig(@HeaderParam(AUTHORIZATION) St
}
return response;
}

/**
* Dummy endpoint to test the http get function with apikey auth config.
*
* @param apikeyHeader apikey header value.
* @return Response.
*/
@GET
@Path("/dummy-get-with-apikey-auth-config")
@Produces("application/json")
public Map<String, String> dummyGetWithApiKeyAuthConfig(@HeaderParam(API_KEY_HEADER) String apikeyHeader) {

Map<String, String> response = new HashMap<>();
if (apikeyHeader != null) {
response.put(STATUS, SUCCESS);
} else {
response.put(STATUS, FAILED);
}
return response;
}

/**
* Dummy endpoint to test the http get function with bearertoken auth config.
*
* @param authorization authorization header value.
* @return Response.
*/
@GET
@Path("/dummy-get-with-bearertoken-auth-config")
@Produces("application/json")
public Map<String, String> dummyGetWithBearerTokenAuthConfig(@HeaderParam(AUTHORIZATION) String authorization) {

Map<String, String> response = new HashMap<>();
if (authorization.startsWith("Bearer")) {
response.put(STATUS, SUCCESS);
} else {
response.put(STATUS, FAILED);
}
return response;
}

/**
* Dummy endpoint to test the http get function with clientcredential auth config.
*
* @param authorization authorization header value.
* @return Response.
*/
@GET
@Path("/dummy-get-with-clientcredential-auth-config")
@Produces("application/json")
public Map<String, String> dummyGetWithClientCredentialAuthConfig(@HeaderParam(AUTHORIZATION) String authorization) {

Map<String, String> response = new HashMap<>();
if (authorization.startsWith("Bearer")) {
response.put(STATUS, SUCCESS);
} else {
response.put(STATUS, FAILED);
}
return response;
}

/**
* Dummy token endpoint to test the http get function with clientcredential auth config.
*
* @param authorization authorization header value.
* @return Response.
*/
@POST
@Path("/dummy-token-endpoint")
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Map<String, String> dummyTokenEndpoint(@HeaderParam("Authorization") String authorization,
@FormParam("grant_type") String grantType) throws JOSEException {

Map<String, String> response = new HashMap<>();
if (grantType.equals("client_credentials")) {
response.put("access_token", generateTestAccessToken());
response.put("scope", "default");
response.put("token_type", "Bearer");
response.put("expires_in", "3600");
return response;
} else {
response.put(STATUS, FAILED);
}
return response;
}
}
Loading

0 comments on commit df48abd

Please sign in to comment.