Skip to content

Commit

Permalink
Backend for keymanager visibility
Browse files Browse the repository at this point in the history
  • Loading branch information
chamilaadhi committed Oct 2, 2024
1 parent 62c00fc commit a33a3dd
Show file tree
Hide file tree
Showing 11 changed files with 156 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
package org.wso2.carbon.apimgt.api.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
Expand All @@ -44,6 +46,7 @@ public class KeyManagerConfigurationDTO implements Serializable {
private String alias = null;
private KeyManagerPermissionConfigurationDTO permissions = new KeyManagerPermissionConfigurationDTO();
private Boolean isUsed = null;
private List<String> allowedOrganizations = new ArrayList<String>();

public KeyManagerConfigurationDTO() {
}
Expand All @@ -62,6 +65,7 @@ public KeyManagerConfigurationDTO(KeyManagerConfigurationDTO keyManagerConfigura
this.externalReferenceId = keyManagerConfigurationDTO.getExternalReferenceId();
this.endpoints = keyManagerConfigurationDTO.getEndpoints();
this.setPermissions(keyManagerConfigurationDTO.getPermissions());
this.allowedOrganizations = keyManagerConfigurationDTO.getAllowedOrganizations();
}
public String getName() {

Expand Down Expand Up @@ -207,4 +211,12 @@ public void setUsed(Boolean isUsed) {

this.isUsed = isUsed;
}

public List<String> getAllowedOrganizations() {
return allowedOrganizations;
}

public void setAllowedOrganizations(List<String> allowedOrganizations) {
this.allowedOrganizations = allowedOrganizations;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9431,6 +9431,7 @@ public List<KeyManagerConfigurationDTO> getKeyManagerConfigurationsByOrganizatio
log.error("Error while converting configurations in " + uuid, e);
}
keyManagerConfigurationDTO.setPermissions(getKeyManagerPermissions(keyManagerConfigurationDTO.getUuid()));
keyManagerConfigurationDTO.setAllowedOrganizations(getKeymanagerVisibleOrgs(uuid));
keyManagerConfigurationDTOS.add(keyManagerConfigurationDTO);
}
}
Expand Down Expand Up @@ -9470,6 +9471,7 @@ public KeyManagerConfigurationDTO getKeyManagerConfigurationByID(String organiza
keyManagerConfigurationDTO.setAdditionalProperties(map);
}
keyManagerConfigurationDTO.setPermissions(getKeyManagerPermissions(keyManagerConfigurationDTO.getUuid()));
keyManagerConfigurationDTO.setAllowedOrganizations(getKeymanagerVisibleOrgs(uuid));
return keyManagerConfigurationDTO;
}
}
Expand Down Expand Up @@ -9541,6 +9543,7 @@ private KeyManagerConfigurationDTO getKeyManagerConfigurationByName(Connection c
keyManagerConfigurationDTO.setAdditionalProperties(map);
}
keyManagerConfigurationDTO.setPermissions(getKeyManagerPermissions(uuid));
keyManagerConfigurationDTO.setAllowedOrganizations(getKeymanagerVisibleOrgs(uuid));
return keyManagerConfigurationDTO;
}
}
Expand Down Expand Up @@ -9583,6 +9586,7 @@ private KeyManagerConfigurationDTO getKeyManagerConfigurationByUUID(Connection c
keyManagerConfigurationDTO.setAdditionalProperties(map);
}
keyManagerConfigurationDTO.setPermissions(getKeyManagerPermissions(uuid));
keyManagerConfigurationDTO.setAllowedOrganizations(getKeymanagerVisibleOrgs(uuid));
return keyManagerConfigurationDTO;
}
}
Expand Down Expand Up @@ -9623,6 +9627,18 @@ public void addKeyManagerConfiguration(KeyManagerConfigurationDTO keyManagerConf
addPermissionStatement.executeBatch();
}
}
List<String> allowedOrgs = keyManagerConfigurationDTO.getAllowedOrganizations();
if (allowedOrgs != null && !allowedOrgs.isEmpty()) {
try (PreparedStatement addVisibleOrgsStatement = conn.prepareStatement(
SQLConstants.KeyManagerOrgVisibilitySqlConstants.ADD_KEY_MANAGER_ORG_VISIBILITY_SQL)) {
for (String org : allowedOrgs) {
addVisibleOrgsStatement.setString(1, keyManagerConfigurationDTO.getUuid());
addVisibleOrgsStatement.setString(2, org);
addVisibleOrgsStatement.addBatch();
}
addVisibleOrgsStatement.executeBatch();
}
}
conn.commit();
} catch (SQLException e) {
conn.rollback();
Expand Down Expand Up @@ -9703,6 +9719,23 @@ public void updateKeyManagerConfiguration(KeyManagerConfigurationDTO keyManagerC
addPermissionStatement.executeBatch();
}
}
try (PreparedStatement deleteOrgStatement = conn.prepareStatement(SQLConstants
.KeyManagerOrgVisibilitySqlConstants.DELETE_ALL_KEY_MANAGER_ORG_VISIBILITY_SQL)) {
deleteOrgStatement.setString(1, keyManagerConfigurationDTO.getUuid());
deleteOrgStatement.executeUpdate();
}
List<String> allowedOrgs = keyManagerConfigurationDTO.getAllowedOrganizations();
if (allowedOrgs != null && !allowedOrgs.isEmpty()) {
try (PreparedStatement addVisibleOrgsStatement = conn.prepareStatement(
SQLConstants.KeyManagerOrgVisibilitySqlConstants.ADD_KEY_MANAGER_ORG_VISIBILITY_SQL)) {
for (String org : allowedOrgs) {
addVisibleOrgsStatement.setString(1, keyManagerConfigurationDTO.getUuid());
addVisibleOrgsStatement.setString(2, org);
addVisibleOrgsStatement.addBatch();
}
addVisibleOrgsStatement.executeBatch();
}
}
conn.commit();
} catch (SQLException e) {
conn.rollback();
Expand Down Expand Up @@ -9775,6 +9808,30 @@ public KeyManagerPermissionConfigurationDTO getKeyManagerPermissions(String keyM
}
return keyManagerPermissions;
}

public List<String> getKeymanagerVisibleOrgs(String keyManagerUUID) throws APIManagementException {
List<String> orgList = new ArrayList<String>();
try (Connection conn = APIMgtDBUtil.getConnection()) {
try {
String getKeyManagerPermissionQuery = SQLConstants.KeyManagerOrgVisibilitySqlConstants.GET_KEY_MANAGER_ORG_VISIBILITY_SQL;
PreparedStatement ps = conn.prepareStatement(getKeyManagerPermissionQuery);
ps.setString(1, keyManagerUUID);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()) {
orgList.add(resultSet.getString("ALLOWED_ORGANIZATIONS"));
}
} catch (SQLException e) {
conn.rollback();
handleException("Failed to get Key Manager organizations information for Key Manager " + keyManagerUUID,
e);
}
} catch (SQLException e) {
throw new APIManagementException(
"Error while retrieving key manager organizations with id " + keyManagerUUID, e);
}
return orgList;
}

public List<KeyManagerConfigurationDTO> getKeyManagerConfigurations() throws APIManagementException {

List<KeyManagerConfigurationDTO> keyManagerConfigurationDTOS = new ArrayList<>();
Expand Down Expand Up @@ -9802,6 +9859,7 @@ public List<KeyManagerConfigurationDTO> getKeyManagerConfigurations() throws API
log.error("Error while converting configurations in " + uuid, e);
}
keyManagerConfigurationDTO.setPermissions(getKeyManagerPermissions(uuid));
keyManagerConfigurationDTO.setAllowedOrganizations(getKeymanagerVisibleOrgs(uuid));
keyManagerConfigurationDTOS.add(keyManagerConfigurationDTO);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3777,6 +3777,24 @@ public static class KeyManagerPermissionsSqlConstants {
" WHERE KEY_MANAGER_UUID = ?";
}

/**
* Static class to hold database queries related to AM_KEY_MANAGER_PERMISSIONS table
*/
public static class KeyManagerOrgVisibilitySqlConstants {

public static final String ADD_KEY_MANAGER_ORG_VISIBILITY_SQL =
" INSERT INTO" +
" AM_KEY_MANAGER_ALLOWED_ORGS (KEY_MANAGER_UUID, ALLOWED_ORGANIZATIONS)" +
" VALUES(?, ?)";

public static final String DELETE_ALL_KEY_MANAGER_ORG_VISIBILITY_SQL = "DELETE FROM AM_KEY_MANAGER_ALLOWED_ORGS" +
" WHERE KEY_MANAGER_UUID = ?";

public static final String GET_KEY_MANAGER_ORG_VISIBILITY_SQL =
"SELECT ALLOWED_ORGANIZATIONS" +
" FROM AM_KEY_MANAGER_ALLOWED_ORGS " +
" WHERE KEY_MANAGER_UUID = ?";
}
/**
* Static class to hold database queries related to AM_TENANT_THEMES table
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ public static TokenTypeEnum fromValue(String v) {
}
}
private TokenTypeEnum tokenType = TokenTypeEnum.DIRECT;
private List<String> allowedOrganizations = new ArrayList<String>();

/**
**/
Expand Down Expand Up @@ -702,6 +703,23 @@ public void setTokenType(TokenTypeEnum tokenType) {
this.tokenType = tokenType;
}

/**
**/
public KeyManagerDTO allowedOrganizations(List<String> allowedOrganizations) {
this.allowedOrganizations = allowedOrganizations;
return this;
}


@ApiModelProperty(value = "")
@JsonProperty("allowedOrganizations")
public List<String> getAllowedOrganizations() {
return allowedOrganizations;
}
public void setAllowedOrganizations(List<String> allowedOrganizations) {
this.allowedOrganizations = allowedOrganizations;
}


@Override
public boolean equals(java.lang.Object o) {
Expand Down Expand Up @@ -746,12 +764,13 @@ public boolean equals(java.lang.Object o) {
Objects.equals(global, keyManager.global) &&
Objects.equals(additionalProperties, keyManager.additionalProperties) &&
Objects.equals(permissions, keyManager.permissions) &&
Objects.equals(tokenType, keyManager.tokenType);
Objects.equals(tokenType, keyManager.tokenType) &&
Objects.equals(allowedOrganizations, keyManager.allowedOrganizations);
}

@Override
public int hashCode() {
return Objects.hash(id, name, displayName, type, description, wellKnownEndpoint, introspectionEndpoint, clientRegistrationEndpoint, tokenEndpoint, displayTokenEndpoint, revokeEndpoint, displayRevokeEndpoint, userInfoEndpoint, authorizeEndpoint, endpoints, certificates, issuer, alias, scopeManagementEndpoint, availableGrantTypes, enableTokenGeneration, enableTokenEncryption, enableTokenHashing, enableMapOAuthConsumerApps, enableOAuthAppCreation, enableSelfValidationJWT, claimMapping, consumerKeyClaim, scopesClaim, tokenValidation, enabled, global, additionalProperties, permissions, tokenType);
return Objects.hash(id, name, displayName, type, description, wellKnownEndpoint, introspectionEndpoint, clientRegistrationEndpoint, tokenEndpoint, displayTokenEndpoint, revokeEndpoint, displayRevokeEndpoint, userInfoEndpoint, authorizeEndpoint, endpoints, certificates, issuer, alias, scopeManagementEndpoint, availableGrantTypes, enableTokenGeneration, enableTokenEncryption, enableTokenHashing, enableMapOAuthConsumerApps, enableOAuthAppCreation, enableSelfValidationJWT, claimMapping, consumerKeyClaim, scopesClaim, tokenValidation, enabled, global, additionalProperties, permissions, tokenType, allowedOrganizations);
}

@Override
Expand Down Expand Up @@ -794,6 +813,7 @@ public String toString() {
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append(" permissions: ").append(toIndentedString(permissions)).append("\n");
sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n");
sb.append(" allowedOrganizations: ").append(toIndentedString(allowedOrganizations)).append("\n");
sb.append("}");
return sb.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,10 @@ public static KeyManagerDTO toKeyManagerDTO(KeyManagerConfigurationDTO keyManage
jsonObject.remove(APIConstants.KeyManager.CONSUMER_KEY_CLAIM);
}
keyManagerDTO.setAdditionalProperties(new Gson().fromJson(jsonObject, Map.class));

if (keyManagerConfigurationDTO.getAllowedOrganizations() != null) {
keyManagerDTO.setAllowedOrganizations(keyManagerConfigurationDTO.getAllowedOrganizations());
}
return keyManagerDTO;
}

Expand Down Expand Up @@ -316,6 +320,10 @@ public static KeyManagerConfigurationDTO toKeyManagerConfigurationDTO(String ten
}
}
keyManagerConfigurationDTO.setEndpoints(endpoints);

if (keyManagerDTO.getAllowedOrganizations() != null) {
keyManagerConfigurationDTO.setAllowedOrganizations(keyManagerDTO.getAllowedOrganizations());
}
additionalProperties
.put(APIConstants.KeyManager.ENABLE_OAUTH_APP_CREATION, keyManagerDTO.isEnableOAuthAppCreation());
additionalProperties.put(APIConstants.KeyManager.ENABLE_MAP_OAUTH_CONSUMER_APPS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4958,7 +4958,10 @@ components:
- EXCHANGED
- DIRECT
- BOTH

allowedOrganizations:
type: array
items:
type: string
KeyManagerEndpoint:
title: Key Manager Endpoint.
required:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4958,7 +4958,10 @@ components:
- EXCHANGED
- DIRECT
- BOTH

allowedOrganizations:
type: array
items:
type: string
KeyManagerEndpoint:
title: Key Manager Endpoint.
required:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil;
import org.wso2.carbon.apimgt.rest.api.store.v1.KeyManagersApiService;
import org.wso2.carbon.apimgt.rest.api.store.v1.mappings.KeyManagerMappingUtil;
import org.wso2.carbon.apimgt.rest.api.store.v1.utils.APIUtils;
import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil;

import java.util.List;
Expand All @@ -36,6 +37,8 @@ public Response keyManagersGet(String xWSO2Tenant, MessageContext messageContext
List<KeyManagerConfigurationDTO> globalKeyManagerConfigurations
= apiAdmin.getGlobalKeyManagerConfigurations();
permittedKeyManagerConfigurations.addAll(globalKeyManagerConfigurations);
permittedKeyManagerConfigurations = APIUtils
.filterAllowedKeyManagersForOrganizations(permittedKeyManagerConfigurations, orgInfo);
return Response.ok(KeyManagerMappingUtil.toKeyManagerListDto(permittedKeyManagerConfigurations, orgInfo))
.build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@

import org.wso2.carbon.apimgt.api.APIConsumer;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIProduct;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.api.model.Environment;
import org.wso2.carbon.apimgt.api.model.OrganizationInfo;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil;
import org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDefaultVersionURLsDTO;
Expand Down Expand Up @@ -199,4 +201,21 @@ public static List<APIEndpointURLsDTO> extractEndpointURLs(APIProduct apiProduct

return apiEndpointsList;
}

public static List<KeyManagerConfigurationDTO> filterAllowedKeyManagersForOrganizations(
List<KeyManagerConfigurationDTO> keymanagerConfigs, OrganizationInfo orgInfo) {

List<KeyManagerConfigurationDTO> allowedList = new ArrayList<KeyManagerConfigurationDTO>();
String organization = orgInfo.getName();
for (KeyManagerConfigurationDTO keyManagerConfigurationDTO : keymanagerConfigs) {
List<String> allowedOrgs = keyManagerConfigurationDTO.getAllowedOrganizations();
// Add to allowedList if no organizations are restricted or if the organization is allowed
if (allowedOrgs == null || allowedOrgs.isEmpty() || allowedOrgs.contains(organization)) {
allowedList.add(keyManagerConfigurationDTO);
}

}

return allowedList;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ public OrganizationInfo getOrganizationInfo(String tenantDomain, String username
orgNameClaim = "http://wso2.org/claims/organization";
}
if (StringUtils.isBlank(orgIdClaim)) {
orgIdClaim = "http://wso2.org/claims/organizationid";
orgIdClaim = "http://wso2.org/claims/organizationId";
}

String organization = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2123,6 +2123,13 @@ CREATE TABLE IF NOT EXISTS AM_KEY_MANAGER_PERMISSIONS (
FOREIGN KEY (KEY_MANAGER_UUID) REFERENCES AM_KEY_MANAGER(UUID) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS AM_KEY_MANAGER_ALLOWED_ORGS (
KEY_MANAGER_UUID VARCHAR(50) NOT NULL,
ALLOWED_ORGANIZATIONS VARCHAR(50) NOT NULL,
PRIMARY KEY (KEY_MANAGER_UUID, ALLOWED_ORGANIZATIONS),
FOREIGN KEY (KEY_MANAGER_UUID) REFERENCES AM_KEY_MANAGER(UUID) ON DELETE CASCADE
);

-- AM_GW_PUBLISHED_API_DETAILS & AM_GW_API_ARTIFACTS are independent tables for Artifact synchronizer feature which --
-- should not have any referential integrity constraints with other tables in AM database--
CREATE TABLE IF NOT EXISTS AM_GW_PUBLISHED_API_DETAILS (
Expand Down

0 comments on commit a33a3dd

Please sign in to comment.