Skip to content

Commit

Permalink
Merge pull request #12461 from YasasRangika/yasas-master
Browse files Browse the repository at this point in the history
Adding support for filtering block conditions based on api context and version
  • Loading branch information
YasasRangika authored Jun 6, 2024
2 parents bf66c58 + 0a32a5b commit 28967ff
Show file tree
Hide file tree
Showing 13 changed files with 167 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,17 @@ APIStateChangeResponse changeLifeCycleStatus(String orgId, ApiTypeWrapper apiTyp
*/
List<BlockConditionsDTO> getBlockConditions() throws APIManagementException;

/**
* Get a lightweight version of list of block Conditions.
*
* @param conditionType type of the condition
* @param conditionValue condition value
* @return list of block conditions
* @throws APIManagementException
*/
List<BlockConditionsDTO> getLightweightBlockConditions(String conditionType, String conditionValue)
throws APIManagementException;

/**
*
* @return Retrieve a block Condition
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,12 @@ public enum ExceptionCodes implements ErrorHandler {
SCOPE_VALIDATION_FAILED(900986, "Scope validation failed", 412, "Scope validation failed"),
SHARED_SCOPE_DISPLAY_NAME_NOT_SPECIFIED(900987, "Shared Scope display name not specified", 400,
"Shared Scope display name not specified"),
BLOCK_CONDITION_RETRIEVE_PARAMS_EXCEPTION(900254, "Block conditions retrieval error", 400,
"Provided query parameters are not valid"),
BLOCK_CONDITION_RETRIEVE_FAILED(900255, "Failed to get Block conditions", 500,
"Failed to retrieve Block conditions from the database"),
INVALID_BLOCK_CONDITION_VALUES(900256, "Error while retrieving Block Conditions", 500,
"Invalid format for condition values"),
SCOPE_ALREADY_ASSIGNED(900988, "Scope already assigned locally by another API", 400,
"Scope already assigned locally by another API"),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1968,6 +1968,8 @@ public enum RegistryResourceTypesForUI {
public static final String BLOCK_CONDITION_ENDING_IP = "endingIp";
public static final String BLOCK_CONDITION_INVERT = "invert";
public static final String BLOCK_CONDITION_IP_TYPE = "type";
public static final String BLOCK_CONDITION_TYPE = "conditionType";
public static final String BLOCK_CONDITION_VALUE = "conditionValue";
public static final String REVOKED_TOKEN_KEY = "revokedToken";
public static final String REVOKED_TOKEN_EXPIRY_TIME = "expiryTime";
public static final String EVENT_TYPE = "eventType";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3679,6 +3679,12 @@ public BlockConditionsDTO getBlockConditionByUUID(String uuid) throws APIManagem
return blockCondition;
}

@Override
public List<BlockConditionsDTO> getLightweightBlockConditions(String conditionType, String conditionValue)
throws APIManagementException {
return apiMgtDAO.getBlockConditionsByConditionTypeAndValue(conditionType, conditionValue, tenantDomain);
}

@Override
public boolean updateBlockCondition(int conditionId, String state) throws APIManagementException {
boolean updateState = apiMgtDAO.updateBlockConditionState(conditionId, state);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13736,24 +13736,60 @@ public List<BlockConditionsDTO> getBlockConditions(String tenantDomain) throws A
selectPreparedStatement.setString(1, tenantDomain);
resultSet = selectPreparedStatement.executeQuery();
while (resultSet.next()) {
BlockConditionsDTO blockConditionsDTO = new BlockConditionsDTO();
blockConditionsDTO.setEnabled(resultSet.getBoolean("ENABLED"));
blockConditionsDTO.setConditionType(resultSet.getString("TYPE"));
blockConditionsDTO.setConditionValue(resultSet.getString("BLOCK_CONDITION"));
blockConditionsDTO.setConditionId(resultSet.getInt("CONDITION_ID"));
blockConditionsDTO.setUUID(resultSet.getString("UUID"));
blockConditionsDTO.setTenantDomain(resultSet.getString("DOMAIN"));
BlockConditionsDTO blockConditionsDTO = populateBlockConditionsDataWithRS(resultSet);
blockConditionsDTOList.add(blockConditionsDTO);
}
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
handleException("Failed to rollback getting Block conditions ", ex);
throw new APIManagementException("Failed to rollback getting Block conditions.",
ExceptionCodes.BLOCK_CONDITION_RETRIEVE_FAILED);
}
}
handleException("Failed to get Block conditions", e);
throw new APIManagementException("Failed to retrieve all block conditions for the tenant " + tenantDomain,
ExceptionCodes.BLOCK_CONDITION_RETRIEVE_FAILED);
} finally {
APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
}
return blockConditionsDTOList;
}

/**
* Retrieves block conditions based on the specified condition type and condition value.
*
* @param conditionType type of the condition
* @param conditionValue condition value
* @param tenantDomain tenant domain
* @return list of block conditions
* @throws APIManagementException
*/
public List<BlockConditionsDTO> getBlockConditionsByConditionTypeAndValue(String conditionType,
String conditionValue, String tenantDomain) throws APIManagementException {
Connection connection = null;
PreparedStatement selectPreparedStatement = null;
ResultSet resultSet = null;
List<BlockConditionsDTO> blockConditionsDTOList = new ArrayList<>();
try {
String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITIONS_BY_TYPE_AND_VALUE_SQL;
connection = APIMgtDBUtil.getConnection();
selectPreparedStatement = connection.prepareStatement(query);
String conditionTypeUpper = conditionType != null ? conditionType.toUpperCase() : null;
selectPreparedStatement.setString(1, conditionTypeUpper);
selectPreparedStatement.setString(2, conditionTypeUpper);
selectPreparedStatement.setString(3, conditionValue);
selectPreparedStatement.setString(4, conditionValue);
selectPreparedStatement.setString(5, tenantDomain);
resultSet = selectPreparedStatement.executeQuery();
while (resultSet.next()) {
BlockConditionsDTO blockConditionsDTO = populateBlockConditionsDataWithRS(resultSet);
blockConditionsDTOList.add(blockConditionsDTO);
}
} catch (SQLException e) {
throw new APIManagementException(
"Failed to get Block conditions by condition type: " + conditionType + " and condition value: "
+ conditionValue, ExceptionCodes.BLOCK_CONDITION_RETRIEVE_FAILED);
} finally {
APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
}
Expand Down Expand Up @@ -21694,4 +21730,16 @@ public void addRevokedConsumerKey(String consumerKey, long revocationTime, Strin
+ e.getMessage(), e);
}
}

private BlockConditionsDTO populateBlockConditionsDataWithRS(ResultSet resultSet) throws SQLException {

BlockConditionsDTO blockConditionsDTO = new BlockConditionsDTO();
blockConditionsDTO.setEnabled(resultSet.getBoolean("ENABLED"));
blockConditionsDTO.setConditionType(resultSet.getString("TYPE"));
blockConditionsDTO.setConditionValue(resultSet.getString("BLOCK_CONDITION"));
blockConditionsDTO.setConditionId(resultSet.getInt("CONDITION_ID"));
blockConditionsDTO.setUUID(resultSet.getString("UUID"));
blockConditionsDTO.setTenantDomain(resultSet.getString("DOMAIN"));
return blockConditionsDTO;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3321,6 +3321,9 @@ public static class ThrottleSQLConstants{
public static final String GET_SUBSCRIPTION_BLOCK_CONDITION_BY_VALUE_AND_DOMAIN_SQL =
"SELECT CONDITION_ID,TYPE,BLOCK_CONDITION,ENABLED,DOMAIN,UUID FROM AM_BLOCK_CONDITIONS WHERE "
+ "BLOCK_CONDITION = ? AND DOMAIN = ? ";
public static final String GET_BLOCK_CONDITIONS_BY_TYPE_AND_VALUE_SQL =
"SELECT CONDITION_ID, TYPE, BLOCK_CONDITION, ENABLED, DOMAIN, UUID FROM AM_BLOCK_CONDITIONS WHERE "
+ "(TYPE = ? OR ? IS NULL) AND (BLOCK_CONDITION LIKE CONCAT('%', ?, '%') OR ? IS NULL) AND DOMAIN = ?";

public static final String TIER_HAS_SUBSCRIPTION = " select count(sub.TIER_ID) as c from AM_SUBSCRIPTION sub, AM_API api "
+ " where sub.TIER_ID = ? and api.API_PROVIDER like ? and sub.API_ID = api.API_ID ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,15 @@ public void testGetBlockConditionByUUID() throws APIManagementException {
}
}

@Test
public void testGetBlockConditionsByConditionTypeAndValue() throws APIManagementException {
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
List<BlockConditionsDTO> list = new ArrayList<>();
Mockito.when(apimgtDAO.getBlockConditionsByConditionTypeAndValue(Mockito.anyString(), Mockito.anyString(),
Mockito.anyString())).thenReturn(list);
assertNotNull(apiProvider.getLightweightBlockConditions("conditionType", "conditionValue"));
}

@Test
public void testUpdateBlockCondition() throws APIManagementException {
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1193,6 +1193,8 @@ public void testAddUpdateDeleteBlockCondition() throws Exception {
BlockConditionsDTO userUUID = apiMgtDAO.addBlockConditions(userBlockcondition);
assertNotNull(apiMgtDAO.getBlockConditionByUUID(apiUUID.getUUID()));
assertNotNull(userUUID);
assertNotNull(apiMgtDAO.getBlockConditionsByConditionTypeAndValue(APIConstants.BLOCKING_CONDITIONS_API,
"/testAddUpdateDeleteBlockCondition", "carbon.super"));
assertNotNull(apiMgtDAO
.updateBlockConditionState(apiMgtDAO.getBlockConditionByUUID(userUUID.getUUID()).getConditionId(),
"FALSE"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ public Response importThrottlingPolicy( @Multipart(value = "file") InputStream f
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. Deny Policies returned ", response = BlockingConditionListDTO.class),
@ApiResponse(code = 406, message = "Not Acceptable. The requested media type is not supported.", response = ErrorDTO.class) })
public Response throttlingDenyPoliciesGet( @ApiParam(value = "Media types acceptable for the response. Default is application/json. " , defaultValue="application/json")@HeaderParam("Accept") String accept) throws APIManagementException{
return delegate.throttlingDenyPoliciesGet(accept, securityContext);
public Response throttlingDenyPoliciesGet( @ApiParam(value = "Media types acceptable for the response. Default is application/json. " , defaultValue="application/json")@HeaderParam("Accept") String accept, @ApiParam(value = "**Search condition**. You can search in attributes by using **\"conditionType:\"** modifier and **\"conditionValue:\"** modifier. Eg. The entry \"conditionType:API\" will result in a match with blocking conditions only if the conditionType is \"API\". Similarly, \"conditionValue:test/1.0.0\" will result in a match with blocking conditions only if the conditionValue is \"test/1.0.0\". When you use \"conditionType:API & conditionValue:test/1.0.0\" as a combination, it will result in a match with blocking conditions only if both the conditionType is \"API\" and the conditionValue is \"test/1.0.0\". If query attribute is provided, this returns the blocking conditions that match the specified attributes. Please note that you need to use encoded URL (URL encoding) if you are using a client which does not support URL encoding (such as curl) ") @QueryParam("query") String query) throws APIManagementException{
return delegate.throttlingDenyPoliciesGet(accept, query, securityContext);
}

@POST
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
public interface ThrottlingApiService {
public Response exportThrottlingPolicy(String policyId, String name, String type, MessageContext messageContext) throws APIManagementException;
public Response importThrottlingPolicy(InputStream fileInputStream, Attachment fileDetail, Boolean overwrite, MessageContext messageContext) throws APIManagementException;
public Response throttlingDenyPoliciesGet(String accept, MessageContext messageContext) throws APIManagementException;
public Response throttlingDenyPoliciesGet(String accept, String query, MessageContext messageContext) throws APIManagementException;
public Response throttlingDenyPoliciesPost(String contentType, BlockingConditionDTO blockingConditionDTO, MessageContext messageContext) throws APIManagementException;
public Response throttlingDenyPolicyConditionIdDelete(String conditionId, MessageContext messageContext) throws APIManagementException;
public Response throttlingDenyPolicyConditionIdGet(String conditionId, MessageContext messageContext) throws APIManagementException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1397,18 +1397,26 @@ private Response resolveUpdateThrottlingPolicy(String policyType, boolean overwr
* @return All matched block conditions to the given request
*/
@Override
public Response throttlingDenyPoliciesGet(String accept, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
List<BlockConditionsDTO> blockConditions = apiProvider.getBlockConditions();
BlockingConditionListDTO listDTO =
BlockingConditionMappingUtil.fromBlockConditionListToListDTO(blockConditions);
return Response.ok().entity(listDTO).build();
} catch (APIManagementException | ParseException e) {
String errorMessage = "Error while retrieving Block Conditions";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
public Response throttlingDenyPoliciesGet(String accept, String query, MessageContext messageContext)
throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
List<BlockConditionsDTO> blockConditions = new ArrayList<>();
// If conditionType and conditionValue are provided, retrieve the block conditions list for the given values.
if (StringUtils.isNotEmpty(query)) {
Map<String, String> parametersMap = BlockingConditionMappingUtil.getQueryParams(query);
if (parametersMap != null && !parametersMap.isEmpty()) {
blockConditions = apiProvider.getLightweightBlockConditions(
parametersMap.get(APIConstants.BLOCK_CONDITION_TYPE),
parametersMap.get(APIConstants.BLOCK_CONDITION_VALUE));
} else {
throw new APIManagementException(ExceptionCodes.BLOCK_CONDITION_RETRIEVE_PARAMS_EXCEPTION);
}
} else {
blockConditions = apiProvider.getBlockConditions();
}
return null;
BlockingConditionListDTO listDTO = BlockingConditionMappingUtil.fromBlockConditionListToListDTO(
blockConditions);
return Response.ok().entity(listDTO).build();
}

/**
Expand Down Expand Up @@ -1465,7 +1473,7 @@ public Response throttlingDenyPoliciesPost(String contentType, BlockingCondition
+ body.getConditionType() + ", " + "value: " + body.getConditionValue() + ". " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (URISyntaxException | ParseException e) {
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving Blocking Condition resource location: Condition type: "
+ body.getConditionType() + ", " + "value: " + body.getConditionValue() + ". " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
Expand Down Expand Up @@ -1499,9 +1507,6 @@ public Response throttlingDenyPolicyConditionIdGet(String conditionId, MessageCo
String errorMessage = "Error while retrieving Block Condition. Id : " + conditionId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (ParseException e) {
String errorMessage = "Error while retrieving Blocking Conditions";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
Expand Down Expand Up @@ -1568,7 +1573,7 @@ public Response throttlingDenyPolicyConditionIdPatch(String conditionId, String
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.DENY_POLICIES, new Gson().toJson(dto),
APIConstants.AuditLogConstants.UPDATED, RestApiCommonUtil.getLoggedInUsername());
return Response.ok().entity(dto).build();
} catch (APIManagementException | ParseException e) {
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_BLOCK_CONDITION, conditionId, e, log);
} else {
Expand Down
Loading

0 comments on commit 28967ff

Please sign in to comment.