Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ public class FSKeyManagerImpl extends WSO2IS7KeyManager {
public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException {

try {
JSONObject spAppData = IdentityServerUtils.getSPApplicationFromClientId(tokenRequest.getClientId());
JSONObject spAppData = IdentityServerUtils
.getSPApplicationFromClientId(super.getKeyManagerConfiguration(), tokenRequest.getClientId());
String regulatoryProperty = IdentityServerUtils.getRegulatoryPropertyFromSPMetadata(spAppData);
if (Boolean.parseBoolean(regulatoryProperty)) {
return null;
Expand Down Expand Up @@ -199,7 +200,6 @@ protected void validateOAuthAppCreationProperties(OAuthApplicationInfo oAuthAppl
@Override
@Generated(message = "Excluding from code coverage since utils methods are covered in other tests")
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws APIManagementException {

HashMap<String, String> additionalProperties = FSKeyManagerUtil
.getValuesForAdditionalProperties(oauthAppRequest);
if (Boolean.parseBoolean(additionalProperties.get(FinancialServicesConstants.REGULATORY))) {
Expand All @@ -213,7 +213,7 @@ public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) t

try {
JSONObject serviceProviderAppData = IdentityServerUtils.getSPApplicationFromClientId(
oAuthApplicationInfo.getClientId());
super.getKeyManagerConfiguration(), oAuthApplicationInfo.getClientId());

if (Boolean.parseBoolean(additionalProperties.get(FinancialServicesConstants.REGULATORY))) {
String appNameProperty = IdentityServerUtils
Expand Down Expand Up @@ -245,7 +245,8 @@ public OAuthApplicationInfo updateApplication(OAuthAppRequest oAuthAppRequest) t
additionalProperties.put(FSKeyManagerConstants.APP_CREATE_REQUEST, FSKeyManagerConstants.FALSE);
OAuthApplicationInfo oAuthApplicationInfo = oAuthAppRequest.getOAuthApplicationInfo();
try {
JSONObject appData = IdentityServerUtils.getSPApplicationFromClientId(oAuthApplicationInfo.getClientId());
JSONObject appData = IdentityServerUtils.getSPApplicationFromClientId(super.getKeyManagerConfiguration(),
oAuthApplicationInfo.getClientId());

doPreUpdateApplication(oAuthAppRequest, additionalProperties, appData);
String appName = appData.getString(FSKeyManagerConstants.NAME);
Expand All @@ -264,7 +265,8 @@ public OAuthApplicationInfo retrieveApplication(String consumerKey) throws APIMa

OAuthApplicationInfo oAuthApplicationInfo = super.retrieveApplication(consumerKey);
try {
JSONObject appData = IdentityServerUtils.getSPApplicationFromClientId(oAuthApplicationInfo.getClientId());
JSONObject appData = IdentityServerUtils.getSPApplicationFromClientId(super.getKeyManagerConfiguration(),
oAuthApplicationInfo.getClientId());
return updateAdditionalProperties(oAuthApplicationInfo,
IdentityServerUtils.getSPMetadataFromSPApp(appData));
} catch (FinancialServicesException e) {
Expand Down Expand Up @@ -295,17 +297,17 @@ protected void updateSpProperties(String spAppName, OAuthApplicationInfo oAuthAp
IdentityServerUtils.getSPMetadataFromSPApp(serviceProviderAppData), additionalProperties);

// Update the DCR application
IdentityServerUtils.updateDCRApplication(serviceProviderAppData.getString(FSKeyManagerConstants.CLIENT_ID),
spAppName, spProperties);
IdentityServerUtils.updateDCRApplication(super.getKeyManagerConfiguration(),
serviceProviderAppData.getString(FSKeyManagerConstants.CLIENT_ID), spAppName, spProperties);

boolean isAppCreateRequest = Boolean.parseBoolean(additionalProperties
.get(FSKeyManagerConstants.APP_CREATE_REQUEST));
boolean isRegulatory = Boolean.parseBoolean(additionalProperties
.get(FinancialServicesConstants.REGULATORY));
if (isAppCreateRequest && isRegulatory) {
String certificate = additionalProperties.get(FSKeyManagerConstants.SP_CERTIFICATE);
IdentityServerUtils.updateSPApplication(serviceProviderAppData
.getString(FSKeyManagerConstants.CLIENT_ID), certificate);
IdentityServerUtils.updateSPApplication(super.getKeyManagerConfiguration(),
serviceProviderAppData.getString(FSKeyManagerConstants.CLIENT_ID), certificate);
}
} catch (FinancialServicesException e) {
log.error("Error while updating service provider application properties", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public class FSKeyManagerConstants {
public static final String API_KEY_VALIDATOR_PASSWORD = "APIKeyValidator.Password";
public static final String API_KEY_VALIDATOR_URL = "APIKeyValidator.ServerURL";
public static final String SERVICE = "/services";
public static final String OAUTH2 = "/oauth2";

public static final String APP_MGMT_API_URL = "/api/server/v1/applications/";
public static final String DCR_EP = "/api/identity/oauth2/dcr/v1.1/register/";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
Expand All @@ -28,6 +29,8 @@
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.financial.services.accelerator.common.constant.FinancialServicesConstants;
import org.wso2.financial.services.accelerator.common.exception.FinancialServicesException;
import org.wso2.financial.services.accelerator.common.util.FinancialServicesUtils;
Expand All @@ -36,7 +39,6 @@

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
Expand All @@ -49,27 +51,25 @@ public class IdentityServerUtils {

/**
* Method to get the application ID from the client ID. Uses Application Management API in IS
* (https://localhost:9446/api/server/v1/applications/) with filter 'clientId eq clientId_value'
* (https://{km_host}:{km_port}/api/server/v1/applications/) with filter 'clientId eq clientId_value'
* to fetch the application ID.
*
* @param keyManagerConfiguration key manager configs configured in APIM
* @param clientId Client ID of the application
* @return Application ID if found, otherwise null
* @throws FinancialServicesException If an error occurs while fetching the application ID
*/
@SuppressFBWarnings("HTTP_PARAMETER_POLLUTION")
public static String getAppIdFromClientId(String clientId) throws FinancialServicesException {
public static String getAppIdFromClientId(final KeyManagerConfiguration keyManagerConfiguration,
final String clientId) throws FinancialServicesException {

try {
String url = getIdentitySeverUrl() + FSKeyManagerConstants.APP_MGMT_API_URL;
URIBuilder builder = new URIBuilder(url);
URIBuilder builder = new URIBuilder(getKeyManagerApplicationMgtEndpoint(keyManagerConfiguration));
builder.addParameter(FSKeyManagerConstants.FILTER, FSKeyManagerConstants.FILTER_KEY + clientId);
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
HttpGet httpGet = new HttpGet(builder.build());

String userName = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_USERNAME);
char[] password = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray();
httpGet.setHeader(FinancialServicesConstants.AUTH_HEADER,
FinancialServicesUtils.getBasicAuthHeader(userName, password));
getBasicAuthHeaderFromKeyManagerConfig(keyManagerConfiguration));
CloseableHttpResponse response = HTTPClientUtils.getHttpsClient().execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new FinancialServicesException("Error while getting app id from client id");
Comment on lines 73 to 75
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 4

Suggested change
CloseableHttpResponse response = HTTPClientUtils.getHttpsClient().execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new FinancialServicesException("Error while getting app id from client id");
CloseableHttpResponse response = HTTPClientUtils.getHttpsClient().execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
log.error("Failed to fetch application ID for clientId: {}. Status: {}", clientId, response.getStatusLine().getStatusCode());
throw new FinancialServicesException("Error while getting app id from client id");

Expand All @@ -88,26 +88,25 @@ public static String getAppIdFromClientId(String clientId) throws FinancialServi

/**
* Method to get the SP application details from the client ID. Uses Application Management API in IS
* (https://localhost:9446/api/server/v1/applications/app_id) to retrieve the SP Application.
* (https://{km_host}:{km_port}/api/server/v1/applications/{app_id}) to retrieve the SP Application.
*
* @param keyManagerConfiguration key manager configs configured in APIM
* @param clientId Client ID of the application
* @return JSONObject containing the SP application details
* @throws FinancialServicesException If an error occurs while fetching the SP application details
*/
public static JSONObject getSPApplicationFromClientId(String clientId) throws FinancialServicesException {
public static JSONObject getSPApplicationFromClientId(final KeyManagerConfiguration keyManagerConfiguration,
final String clientId) throws FinancialServicesException {

String appId = getAppIdFromClientId(clientId);
final String appId = getAppIdFromClientId(keyManagerConfiguration, clientId);

try {
String url = getIdentitySeverUrl() + FSKeyManagerConstants.APP_MGMT_API_URL + appId;
final String url = getKeyManagerApplicationMgtEndpoint(keyManagerConfiguration) + appId;
URIBuilder builder = new URIBuilder(url);
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
HttpGet httpGet = new HttpGet(builder.build());

String userName = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_USERNAME);
char[] password = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray();
httpGet.setHeader(FinancialServicesConstants.AUTH_HEADER,
FinancialServicesUtils.getBasicAuthHeader(userName, password));
getBasicAuthHeaderFromKeyManagerConfig(keyManagerConfiguration));
CloseableHttpResponse response = HTTPClientUtils.getHttpsClient().execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new FinancialServicesException("Error while getting sp application from client id");
Expand All @@ -121,19 +120,21 @@ public static JSONObject getSPApplicationFromClientId(String clientId) throws Fi

/**
* Method to update the SP application in the Identity server with the provided certificate. Uses Application
* Management API in IS (https://localhost:9446/api/server/v1/applications/).
* Management API in IS (https://{km_host}:{km_port}/api/server/v1/applications/).
*
* @param keyManagerConfiguration key manager configs configured in APIM
* @param clientId Client ID of the application
* @param certificate Certificate content in PEM format to be updated in the SP application
* @throws FinancialServicesException If an error occurs while updating the SP application
*/
public static void updateSPApplication(String clientId, String certificate)
public static void updateSPApplication(final KeyManagerConfiguration keyManagerConfiguration,
final String clientId, final String certificate)
throws FinancialServicesException {

String appId = getAppIdFromClientId(clientId);
final String appId = getAppIdFromClientId(keyManagerConfiguration, clientId);

try {
String url = getIdentitySeverUrl() + FSKeyManagerConstants.APP_MGMT_API_URL + appId;
String url = getKeyManagerApplicationMgtEndpoint(keyManagerConfiguration) + appId;
URIBuilder builder = new URIBuilder(url);
HttpPatch httpPatch = new HttpPatch(builder.build());

Expand All @@ -144,11 +145,8 @@ public static void updateSPApplication(String clientId, String certificate)
FinancialServicesConstants.JSON_CONTENT_TYPE);
httpPatch.setHeader(FinancialServicesConstants.ACCEPT,
FinancialServicesConstants.JSON_CONTENT_TYPE);

String userName = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_USERNAME);
char[] password = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray();
httpPatch.setHeader(FinancialServicesConstants.AUTH_HEADER,
FinancialServicesUtils.getBasicAuthHeader(userName, password));
getBasicAuthHeaderFromKeyManagerConfig(keyManagerConfiguration));
CloseableHttpResponse response = HTTPClientUtils.getHttpsClient().execute(httpPatch);
if (response.getStatusLine().getStatusCode() != 200) {
throw new FinancialServicesException("Error while getting sp application from client id");
Expand Down Expand Up @@ -178,31 +176,30 @@ private static JSONObject constructAppUpdatePayload(String certificateContent) {

/**
* Method to update the DCR application in the Identity server. Used DCR API in IS
* ("https://localhost:9446/api/identity/oauth2/dcr/v1.1/register/").
* ("https://{km_host}:{km_port}/api/identity/oauth2/dcr/v1.1/register/").
*
* @param clientId Client ID of the application
* @param appName Application name
* @param attributes Map of attributes to be updated
* @throws FinancialServicesException If an error occurs while updating the application
*/
public static void updateDCRApplication(String clientId, String appName, Map<String, Object> attributes)
public static void updateDCRApplication(final KeyManagerConfiguration keyManagerConfiguration,
String clientId, String appName, Map<String, Object> attributes)
throws FinancialServicesException {

JSONObject spApplication = constructDCRUpdatePayload(appName, attributes);

try {
String url = getIdentitySeverUrl() + FSKeyManagerConstants.DCR_EP + clientId;
String url = getKeyManagerBaseUrl(keyManagerConfiguration) + FSKeyManagerConstants.DCR_EP + clientId;
URIBuilder builder = new URIBuilder(url);
HttpPut httpPut = new HttpPut(builder.build());
StringEntity params = new StringEntity(spApplication.toString());
httpPut.setEntity(params);
httpPut.setHeader(FinancialServicesConstants.CONTENT_TYPE_TAG,
FinancialServicesConstants.JSON_CONTENT_TYPE);

String userName = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_USERNAME);
char[] password = getAPIMgtConfig(FSKeyManagerConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray();
httpPut.setHeader(FinancialServicesConstants.AUTH_HEADER,
FinancialServicesUtils.getBasicAuthHeader(userName, password));
getBasicAuthHeaderFromKeyManagerConfig(keyManagerConfiguration));
CloseableHttpResponse response = HTTPClientUtils.getHttpsClient().execute(httpPut);
if (response.getStatusLine().getStatusCode() != 200) {
throw new FinancialServicesException("Error while updating sp application");
Expand Down Expand Up @@ -335,4 +332,42 @@ public static String getSpPropertyFromSPMetaData(String propertyName, JSONArray
return propertyValue;
}

/**
* Method to get the key manager /applications endpoint.
*
* @return the URL of the /applications REST endpoint.
*/
public static String getKeyManagerApplicationMgtEndpoint(final KeyManagerConfiguration keyManagerConfiguration) {

return getKeyManagerBaseUrl(keyManagerConfiguration) + FSKeyManagerConstants.APP_MGMT_API_URL;
}

/**
* Method to get the basic auth header value from key manager configs.
*
* @return basic auth header value.
*/
public static String getBasicAuthHeaderFromKeyManagerConfig(KeyManagerConfiguration keyManagerConfiguration) {

String userName = (String) keyManagerConfiguration.getParameter(APIConstants.KEY_MANAGER_USERNAME);
char[] password = ((String) keyManagerConfiguration.getParameter(APIConstants.KEY_MANAGER_PASSWORD))
.toCharArray();
return FinancialServicesUtils.getBasicAuthHeader(userName, password);
}

/**
* Method to get the key manager base URL.
*
* @return key manager base URL.
*/
private static String getKeyManagerBaseUrl(final KeyManagerConfiguration keyManagerConfiguration) {

final String keyManagerAuthEndpoint =
(String) keyManagerConfiguration.getParameter(APIConstants.KeyManager.AUTHORIZE_ENDPOINT);
if (StringUtils.isNotEmpty(keyManagerAuthEndpoint)) {
return keyManagerAuthEndpoint.split(FSKeyManagerConstants.OAUTH2)[0];
}
return getIdentitySeverUrl();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public void tearDown() {

@Test
public void testGetNewApplicationAccessToken() throws APIManagementException {
identityServerUtilsMockedStatic.when(() -> IdentityServerUtils.getSPApplicationFromClientId(anyString()))
identityServerUtilsMockedStatic.when(() -> IdentityServerUtils.getSPApplicationFromClientId(any(), anyString()))
.thenReturn(new JSONObject());
identityServerUtilsMockedStatic.when(() -> IdentityServerUtils.getRegulatoryPropertyFromSPMetadata(any()))
.thenReturn("true");
Expand All @@ -113,7 +113,7 @@ public void testGetNewApplicationAccessToken() throws APIManagementException {

@Test
public void testGetNewApplicationAccessTokenWithException() {
identityServerUtilsMockedStatic.when(() -> IdentityServerUtils.getSPApplicationFromClientId(anyString()))
identityServerUtilsMockedStatic.when(() -> IdentityServerUtils.getSPApplicationFromClientId(any(), anyString()))
.thenThrow(new FinancialServicesException("Error retrieving SP application"));

AccessTokenRequest accessTokenRequest = Mockito.mock(AccessTokenRequest.class);
Expand Down
Loading