scope-role-permission refactoring and webapp authorization

kernel-4.6.x
Amalka Subasinghe 3 years ago
parent 438814eedd
commit 94dd33ffa5

@ -37,7 +37,7 @@
</servlet-mapping>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
<param-value>false</param-value>
</context-param>
<!--This is to support basic auth.-->
<context-param>

@ -18,6 +18,8 @@
*/
package org.wso2.carbon.apimgt.webapp.publisher;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.FaultGatewaysException;
@ -32,7 +34,6 @@ import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate;
import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
@ -61,11 +62,26 @@ public class APIPublisherServiceImpl implements APIPublisherService {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(apiConfig.getOwner());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
APIProvider apiProvider = API_MANAGER_FACTORY.getAPIProvider(apiConfig.getOwner());
API api = getAPI(apiConfig);
APIIdentifier apiIdentifier = new APIIdentifier(apiConfig.getOwner(), apiConfig.getName(), apiConfig.getVersion());
if (!apiProvider.isAPIAvailable(apiIdentifier)) {
if (!apiProvider.isAPIAvailable(api.getId())) {
// add new scopes as shared scopes
Set<String> allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain);
for (ApiScope apiScope : apiConfig.getScopes()) {
if (!allSharedScopeKeys.contains(apiScope.getKey())) {
Scope scope = new Scope();
scope.setName(apiScope.getName());
scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain);
}
}
API api = getAPI(apiConfig, true);
API createdAPI = apiProvider.addAPI(api);
if (CREATED_STATUS.equals(createdAPI.getStatus())) {
apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null);
@ -73,6 +89,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiRevision.setApiUUID(createdAPI.getUuid());
apiRevision.setDescription("Initial Revision");
String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain);
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setVhost("localhost");
@ -85,14 +102,83 @@ public class APIPublisherServiceImpl implements APIPublisherService {
}
} else {
if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
API existingAPI = apiProvider.getAPI(api.getId());
// With 4.x to 5.x upgrade
// - there cannot be same local scope assigned in 2 different APIs
// - local scopes will be deprecated in the future, so need to move all scopes as shared scopes
// if an api scope is not available as shared scope, but already assigned as local scope -> that means, the scopes available for this API has not moved as shared scopes
// in order to do that :
// 1. update the same API removing scopes from URI templates
// 2. add scopes as shared scopes
// 3. update the API again adding scopes for the URI Templates
// if an api scope is not available as shared scope, and not assigned as local scope -> that means, there are new scopes
// 1. add new scopes as shared scopes
// 2. update the API adding scopes for the URI Templates
Set<String> allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain);
Set<ApiScope> scopesToMoveAsSharedScopes = new HashSet<>();
for (ApiScope apiScope : apiConfig.getScopes()) {
// if the scope is not available as shared scope and it is assigned to an API as a local scope
// need remove the local scope and add as a shared scope
if (!allSharedScopeKeys.contains(apiScope.getKey())) {
if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) {
// collect scope to move as shared scopes
scopesToMoveAsSharedScopes.add(apiScope);
} else {
// if new scope add as shared scope
Scope scope = new Scope();
scope.setName(apiScope.getName());
scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain);
}
} else {
// if already available as shared scope -> update
Scope scope = new Scope();
scope.setName(apiScope.getName());
scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles());
apiProvider.updateSharedScope(scope, tenantDomain);
}
}
// Get existing API
API existingAPI = apiProvider.getAPI(apiIdentifier);
if (scopesToMoveAsSharedScopes.size() > 0) {
// update API to remove local scopes
API api = getAPI(apiConfig, false);
api.setStatus(existingAPI.getStatus());
apiProvider.updateAPI(api);
for (ApiScope apiScope : scopesToMoveAsSharedScopes) {
Scope scope = new Scope();
scope.setName(apiScope.getName());
scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain);
}
}
existingAPI = apiProvider.getAPI(apiIdentifier);
API api = getAPI(apiConfig, true);
api.setStatus(existingAPI.getStatus());
apiProvider.updateAPI(api);
if (api.getId().getName().equals(existingAPI.getId().getName()) &&
api.getId().getVersion().equals(existingAPI.getId().getVersion())) {
if (CREATED_STATUS.equals(existingAPI.getStatus())) {
apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null);
}
if (CREATED_STATUS.equals(existingAPI.getStatus())) {
apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null);
APIRevision apiRevision = new APIRevision();
apiRevision.setApiUUID(existingAPI.getUuid());
apiRevision.setDescription("Updated Revision");
String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain);
List<APIRevisionDeployment> apiRevisionDeploymentList = apiProvider.getAPIRevisionDeploymentList(apiRevisionId);
apiProvider.deployAPIRevision(existingAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList);
}
}
}
@ -105,7 +191,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
}
}
private API getAPI(APIConfig config) {
private API getAPI(APIConfig config, boolean includeScopes) {
APIIdentifier apiIdentifier = new APIIdentifier(config.getOwner(), config.getName(), config.getVersion());
API api = new API(apiIdentifier);
@ -129,13 +215,15 @@ public class APIPublisherServiceImpl implements APIPublisherService {
uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb());
uriTemplate.setResourceURI(apiUriTemplate.getResourceURI());
uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate());
Scope scope = new Scope();
if (apiUriTemplate.getScope() != null) {
scope.setName(apiUriTemplate.getScope().getName());
scope.setDescription(apiUriTemplate.getScope().getDescription());
scope.setKey(apiUriTemplate.getScope().getKey());
scope.setRoles(apiUriTemplate.getScope().getRoles());
uriTemplate.setScope(scope);
if (includeScopes) {
Scope scope = new Scope();
if (apiUriTemplate.getScope() != null) {
scope.setName(apiUriTemplate.getScope().getName());
scope.setDescription(apiUriTemplate.getScope().getDescription());
scope.setKey(apiUriTemplate.getScope().getKey());
scope.setRoles(apiUriTemplate.getScope().getRoles());
uriTemplate.setScopes(scope);
}
}
uriTemplates.add(uriTemplate);
}

@ -23,6 +23,7 @@ public class ApiScope {
String key;
String name;
String roles;
String permissions;
String description;
int id;
@ -61,4 +62,11 @@ public class ApiScope {
this.description = description;
}
public String getPermissions() {
return permissions;
}
public void setPermissions(String permissions) {
this.permissions = permissions;
}
}

@ -70,6 +70,7 @@ public class AnnotationProcessor {
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_DESCRIPTION = "description";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_KEY = "key";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_PERMISSIONS = "permissions";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_ROLES = "roles";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_VERSION = "version";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_CONTEXT = "context";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_VALUE = "value";
@ -78,6 +79,7 @@ public class AnnotationProcessor {
private static final String DEFAULT_SCOPE_NAME = "default admin scope";
private static final String DEFAULT_SCOPE_KEY = "perm:admin";
private static final String DEFAULT_SCOPE_PERMISSION = "/permision/device-mgt";
private static final String DEFAULT_SCOPE_ROLE = "admin";
private static final String PERMISSION_PREFIX = "/permission/admin";
@ -217,8 +219,11 @@ public class AnnotationProcessor {
ApiScope scope;
String permissions[];
StringBuilder aggregatedPermissions;
String roles[];
StringBuilder aggregatedRoles;
for(int i=0; i<annotatedScopes.length; i++){
aggregatedPermissions = new StringBuilder();
aggregatedRoles = new StringBuilder();
methodHandler = Proxy.getInvocationHandler(annotatedScopes[i]);
scope = new ApiScope();
scope.setName(invokeMethod(scopeClass
@ -234,7 +239,14 @@ public class AnnotationProcessor {
aggregatedPermissions.append(permission);
aggregatedPermissions.append(" ");
}
scope.setRoles(aggregatedPermissions.toString().trim());
scope.setPermissions(aggregatedPermissions.toString().trim());
roles = (String[])methodHandler.invoke(annotatedScopes[i], scopeClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_ROLES, null),null);
for (String role : roles) {
aggregatedRoles.append(role);
aggregatedRoles.append(",");
}
scope.setRoles(aggregatedRoles.substring(0, aggregatedRoles.lastIndexOf(",")));
scopes.put(scope.getKey(), scope);
}
return scopes;
@ -288,7 +300,8 @@ public class AnnotationProcessor {
scope.setName(DEFAULT_SCOPE_NAME);
scope.setDescription(DEFAULT_SCOPE_NAME);
scope.setKey(DEFAULT_SCOPE_KEY);
scope.setRoles(DEFAULT_SCOPE_PERMISSION);
scope.setRoles(DEFAULT_SCOPE_ROLE);
scope.setPermissions(DEFAULT_SCOPE_PERMISSION);
resource.setScope(scope);
}
}

@ -86,12 +86,14 @@ import javax.ws.rs.core.Response;
name = "Get ApplicationDTO Details",
description = "Get application details",
key = "perm:app:publisher:view",
roles = {"Internal/everyone"},
permissions = {"/app-mgt/publisher/application/view"}
),
@Scope(
name = "Update an ApplicationDTO",
description = "Update an application",
key = "perm:app:publisher:update",
roles = {"Internal/everyone"},
permissions = {"/app-mgt/publisher/application/update"}
)
}

@ -68,6 +68,7 @@ import java.util.List;
name = "Delete Application Release",
description = "Delete Application Release",
key = "perm:admin:app:publisher:update",
roles = {"admin"},
permissions = {"/app-mgt/publisher/admin/application/update"}
)
}

@ -65,12 +65,14 @@ scopes = {
name = "Update a Review",
description = "Update a Review of application.",
key = "perm:admin:app:review:update",
roles = {"admin"},
permissions = {"/app-mgt/publisher/admin/review/update"}
),
@Scope(
name = "Get Review Details",
description = "Get review details of application.",
key = "perm:admin:app:review:view",
roles = {"admin"},
permissions = {"/app-mgt/publisher/admin/review/view"}
)
}

@ -68,6 +68,7 @@ import javax.ws.rs.core.Response;
name = "Get Application Details",
description = "Get application details",
key = "perm:app:store:view",
roles = {"Internal/everyone"},
permissions = {"/app-mgt/store/application/view"}
)
}

@ -73,12 +73,14 @@ import java.util.List;
name = "Get Review Details",
description = "Get review details from application store.",
key = "perm:app:review:view",
roles = {"Internal/everyone"},
permissions = {"/app-mgt/store/review/view"}
),
@Scope(
name = "Update a Review",
description = "Update a Review from the application store.",
key = "perm:app:review:update",
roles = {"Internal/everyone"},
permissions = {"/app-mgt/store/review/update"}
),
}

@ -27,6 +27,7 @@ import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -65,16 +66,18 @@ import java.util.List;
)
@Scopes(
scopes = {
@org.wso2.carbon.apimgt.annotations.api.Scope(
@Scope(
name = "Install an ApplicationDTO",
description = "Install an application",
key = "perm:app:subscription:install",
roles = {"Internal/everyone"},
permissions = {"/app-mgt/store/subscription/install"}
),
@org.wso2.carbon.apimgt.annotations.api.Scope(
@Scope(
name = "Uninstall an Application",
description = "Uninstall an application",
key = "perm:app:subscription:uninstall",
roles = {"Internal/everyone"},
permissions = {"/app-mgt/store/subscription/uninstall"}
)
}

@ -63,6 +63,7 @@ scopes = {
name = "Update a Review",
description = "Update a Review of applications.",
key = "perm:admin:app:review:update",
roles = {"admin"},
permissions = {"/app-mgt/store/admin/review/update"}
)
}

@ -67,6 +67,7 @@ import java.util.List;
name = "View Application Subscriptions",
description = "View Application Subscriptions.",
key = "perm:admin:app:subscription:view",
roles = {"admin"},
permissions = {"/app-mgt/store/admin/subscription/view"}
)
}

@ -41,6 +41,7 @@ import javax.ws.rs.core.Response;
name = "Sign CSR",
description = "Sign CSR",
key = "perm:sign-csr",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/certificates/manage"}
)
}

@ -45,30 +45,35 @@ import javax.ws.rs.core.Response;
name = "Adding a new SSL certificate",
description = "Adding a new SSL certificate",
key = "perm:admin:certificates:add",
roles = {"admin"},
permissions = {"/device-mgt/admin/certificates/add"}
),
@Scope(
name = "Getting Details of an SSL Certificate",
description = "Getting Details of an SSL Certificate",
key = "perm:admin:certificates:details",
roles = {"admin"},
permissions = {"/device-mgt/admin/certificates/details"}
),
@Scope(
name = "Getting Details of Certificates",
description = "Getting Details of Certificates",
key = "perm:admin:certificates:view",
roles = {"admin"},
permissions = {"/device-mgt/admin/certificates/view"}
),
@Scope(
name = "Deleting an SSL Certificate",
description = "Deleting an SSL Certificate",
key = "perm:admin:certificates:delete",
roles = {"admin"},
permissions = {"/device-mgt/admin/certificates/delete"}
),
@Scope(
name = "Verify SSL certificate",
description = "Verify SSL certificate",
key = "perm:admin:certificates:verify",
roles = {"admin"},
permissions = {"/device-mgt/admin/certificates/verify"}
)
}

@ -71,24 +71,28 @@ import java.util.List;
name = "View configurations",
description = "",
key = "perm:view-configuration",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/platform-configurations/view"}
),
@Scope(
name = "Manage configurations",
description = "",
key = "perm:manage-configuration",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/platform-configurations/manage"}
),
@Scope(
name = "Getting Details of Device tenants",
description = "Getting Details of Device tenants",
key = "perm:admin:tenant:view",
roles = {"Internal/everyone"},
permissions = {"/tenants/view"}
),
@Scope(
name = "Add a permission to the permission tree",
description = "Add a permission to the permission tree",
key = "perm:admin:permissions:add",
roles = {"Internal/everyone"},
permissions = {"/permissions/add"}
)
}

@ -37,13 +37,13 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.general.TenantDetail;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.config.keymanager.KeyManagerConfigurations;
import org.wso2.carbon.device.mgt.core.config.ui.UIConfiguration;
import org.wso2.carbon.device.mgt.core.config.ui.UIConfigurationManager;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
@ -274,15 +274,16 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
@Path("/permissions")
@Produces({MediaType.APPLICATION_JSON})
public Response addPermission(List<String> permissions) {
PermissionManagerService permissionService = DeviceMgtAPIUtils.getPermissionManagerService();
org.wso2.carbon.device.mgt.common.permission.mgt.Permission permission = new org
.wso2.carbon.device.mgt.common.permission.mgt.Permission();
// PermissionManagerService permissionService = DeviceMgtAPIUtils.getPermissionManagerService();
// org.wso2.carbon.device.mgt.common.permission.mgt.Permission permission = new org
// .wso2.carbon.device.mgt.common.permission.mgt.Permission();
for (String path : permissions) {
permission.setPath(path);
permission.setUrl(path);
// permission.setPath(path);
// permission.setUrl(path);
try {
permissionService.addPermission(permission);
PermissionUtils.putPermission(path);
// permissionService.addPermission(permission);
} catch (PermissionManagementException e) {
String msg = "Error occurred adding permission";
log.error(msg, e);

@ -21,7 +21,6 @@ package io.entgra.carbon.device.mgt.config.jaxrs.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.user.core.service.RealmService;
@ -33,7 +32,6 @@ public class DeviceMgtAPIUtils {
private static final Log log = LogFactory.getLog(DeviceMgtAPIUtils.class);
private static DeviceManagementProviderService deviceManagementProviderService = null;
private static PermissionManagerService permissionManagerService = null;
private static RealmService realmService = null;
public static DeviceManagementProviderService getDeviceManagementService() {
@ -50,20 +48,6 @@ public class DeviceMgtAPIUtils {
return deviceManagementProviderService;
}
public static PermissionManagerService getPermissionManagerService() {
if (permissionManagerService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
permissionManagerService =
(PermissionManagerService) ctx.getOSGiService(PermissionManagerService.class, null);
if (permissionManagerService == null) {
String msg = "Permission Management provider service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return permissionManagerService;
}
public static RealmService getRealmService() {
if (realmService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();

@ -76,6 +76,7 @@ import javax.ws.rs.core.Response;
name = "Get activities",
description = "Get activities",
key = "perm:get-activity",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
)
}

@ -68,41 +68,49 @@ import javax.ws.rs.core.Response;
name = "Create Event Stream Artifact",
description = "Create Event Stream Artifact",
key = "perm:analytics:artifacts:stream",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/stream/add"}),
@Scope(
name = "Delete Stream Artifact",
description = "Delete Stream Artifact",
key = "perm:analytics:artifacts:stream:delete",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/stream/delete"}),
@Scope(
name = "Create Event Receiver Artifact",
description = "Create Event Receiver Artifact",
key = "perm:analytics:artifacts:receiver",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/receiver/add"}),
@Scope(
name = "Delete Receiver Artifact",
description = "Delete Receiver Artifact",
key = "perm:analytics:artifacts:receiver:delete",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/receiver/delete"}),
@Scope(
name = "Create Event Publisher Artifact",
description = "Create Event Publisher Artifact",
key = "perm:analytics:artifacts:publisher",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/publisher/add"}),
@Scope(
name = "Delete Publisher Artifact",
description = "Delete Publisher Artifact",
key = "perm:analytics:artifacts:publisher:delete",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/publisher/delete"}),
@Scope(
name = "Create Siddhi Script Artifact",
description = "Create Siddhi Script Artifact",
key = "perm:analytics:artifacts:siddhi",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/siddhi-script/add"}),
@Scope(
name = "Delete Siddhi Script Artifact",
description = "Delete Siddhi Script Artifact",
key = "perm:analytics:artifacts:siddhi:delete",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/analytics/artifacts/siddhi-script/delete"})
}
)

@ -69,12 +69,14 @@ import javax.ws.rs.core.Response;
name = "View configurations",
description = "",
key = "perm:view-configuration",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/platform-configurations/view"}
),
@Scope(
name = "Manage configurations",
description = "",
key = "perm:manage-configuration",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/platform-configurations/manage"}
)
}

@ -77,30 +77,35 @@ import java.util.Map;
name = "Enroll Device",
description = "Register a device",
key = "perm:device:enroll",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/add"}
),
@Scope(
name = "Modify Device",
description = "Modify a device",
key = "perm:device:modify",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/modify"}
),
@Scope(
name = "Disenroll Device",
description = "Disenroll a device",
key = "perm:device:disenroll",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/remove"}
),
@Scope(
name = "Publish Event",
description = "publish device event",
key = "perm:device:publish-event",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/event"}
),
@Scope(
name = "Getting Device Operation Details",
description = "Getting Device Operation Details",
key = "perm:device:operations",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
)
}

@ -51,12 +51,14 @@ import javax.ws.rs.core.Response;
name = "Add or Delete Event Definition for device type",
description = "Add or Delete Event Definition for device type",
key = "perm:device-types:events",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/device-type/add"}
),
@Scope(
name = "Get Events Details of a Device Type",
description = "Get Events Details of a Device Type",
key = "perm:device-types:events:view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
)
}

@ -107,66 +107,77 @@ import java.util.List;
name = "Getting Details of Registered Devices",
description = "Getting Details of Registered Devices",
key = "perm:devices:view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Getting Details of a Device",
description = "Getting Details of a Device",
key = "perm:devices:details",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Update the device specified by device id",
description = "Update the device specified by device id",
key = "perm:devices:update",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Delete the device specified by device id",
description = "Delete the device specified by device id",
key = "perm:devices:delete",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Getting Feature Details of a Device",
description = "Getting Feature Details of a Device",
key = "perm:devices:features",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Advanced Search for Devices",
description = "Advanced Search for Devices",
key = "perm:devices:search",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Getting Installed Application Details of a Device",
description = "Getting Installed Application Details of a Device",
key = "perm:devices:applications",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Getting Device Operation Details",
description = "Getting Device Operation Details",
key = "perm:devices:operations",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Get the details of the policy that is enforced on a device.",
description = "Get the details of the policy that is enforced on a device.",
key = "perm:devices:effective-policy",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Getting Policy Compliance Details of a Device",
description = "Getting Policy Compliance Details of a Device",
key = "perm:devices:compliance-data",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Change device status.",
description = "Change device status.",
key = "perm:devices:change-status",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/change-status"}
),
}

@ -87,24 +87,28 @@ import javax.ws.rs.core.Response;
name = "Getting the Supported Device Platforms",
description = "Getting the Supported Device Platforms",
key = "perm:device-types:types",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/device-type/view"}
),
@Scope(
name = "Get Feature Details of a Device Type",
description = "Get Feature Details of a Device Type",
key = "perm:device-types:features",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/device-type/features/view"}
),
@Scope(
name = "Get Config Details of a Device Type",
description = "Get Config Details of a Device Type",
key = "perm:device-types:configs",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/device-type/config/view"}
),
@Scope(
name = "Getting Details of Policies",
description = "Getting Details of Policies",
key = "perm:policies:get-details",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/view"}
)
}

@ -73,18 +73,21 @@ import java.util.List;
name = "View Analytics",
description = "",
key = "perm:geo-service:analytics-view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view-analytics"}
),
@Scope(
name = "Manage Alerts",
description = "",
key = "perm:geo-service:alerts-manage",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/manage-alerts"}
),
@Scope(
name = "Manage Geo Fences",
description = "",
key = "perm:geo-service:geo-fence",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/manage-geo-fence"}
)
}

@ -82,84 +82,98 @@ import java.util.List;
name = "Get the list of groups belongs to current user.",
description = "Get the list of groups belongs to current user.",
key = "perm:groups:groups",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/view"}
),
@Scope(
name = "Get the count of groups belongs to current user.",
description = "Get the count of groups belongs to current user.",
key = "perm:groups:count",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/view"}
),
@Scope(
name = "Add new device group to the system.",
description = "Add new device group to the system.",
key = "perm:groups:add",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/add"}
),
@Scope(
name = "View group specified",
description = "View group specified",
key = "perm:groups:groups-view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/view"}
),
@Scope(
name = "Update a group",
description = "Update a group",
key = "perm:groups:update",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/update"}
),
@Scope(
name = "Delete a group",
description = "Delete a group",
key = "perm:groups:remove",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/remove"}
),
@Scope(
name = "Manage group sharing with a user",
description = "Manage group sharing with a user",
key = "perm:groups:share",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/share"}
),
@Scope(
name = "View list of roles of a device group",
description = "View list of roles of a device group",
key = "perm:groups:roles",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/roles/view"}
),
@Scope(
name = "View list of devices in the device group",
description = "View list of devices in the device group",
key = "perm:groups:devices",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/devices/view"}
),
@Scope(
name = "View list of device count in the device group",
description = "View list of device count in the device group",
key = "perm:groups:devices-count",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/devices/view"}
),
@Scope(
name = "Add devices to group",
description = "Add devices to group",
key = "perm:groups:devices-add",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/devices/add"}
),
@Scope(
name = "Remove devices from group",
description = "Remove devices from group",
key = "perm:groups:devices-remove",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/devices/remove"}
),
@Scope(
name = "Assign devices to groups",
description = "Assign devices to groups",
key = "perm:groups:assign",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/devices/add"}
),
@Scope(
name = "List of groups that have the device",
description = "List of groups that have the device",
key = "perm:groups:device",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/groups/devices/view"}
)
}

@ -73,24 +73,28 @@ import javax.ws.rs.core.Response;
name = "View metadata records",
description = "View metadata records",
key = "perm:metadata:view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/metadata/view"}
),
@Scope(
name = "Create a metadata record",
description = "Create a metadata record",
key = "perm:metadata:create",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/metadata/create"}
),
@Scope(
name = "Update a metadata record",
description = "Updating a specified metadata record",
key = "perm:metadata:update",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/metadata/update"}
),
@Scope(
name = "Delete a metadata record",
description = "Delete a specified metadata record",
key = "perm:metadata:remove",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/metadata/remove"}
)
}

@ -73,12 +73,14 @@ import javax.ws.rs.core.Response;
name = "Getting All Device Notification Details",
description = "Getting All Device Notification Details",
key = "perm:notifications:view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/notifications/view"}
),
@Scope(
name = "Updating the Device Notification Status",
description = "Updating the Device Notification Status",
key = "perm:notifications:mark-checked",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/notifications/view"}
)
}

@ -79,60 +79,70 @@ import java.util.List;
name = "Adding a Policy",
description = "Adding a Policy",
key = "perm:policies:manage",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/manage"}
),
@Scope(
name = "Getting Details of Policies",
description = "Getting Details of Policies",
key = "perm:policies:get-details",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/view"}
),
@Scope(
name = "Getting Details of a Policy",
description = "Getting Details of a Policy",
key = "perm:policies:get-policy-details",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/view"}
),
@Scope(
name = "Updating a Policy",
description = "Updating a Policy",
key = "perm:policies:update",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/manage"}
),
@Scope(
name = "Removing Multiple Policies",
description = "Removing Multiple Policies",
key = "perm:policies:remove",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/manage"}
),
@Scope(
name = "Activating Policies",
description = "Activating Policies",
key = "perm:policies:activate",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/manage"}
),
@Scope(
name = "Deactivating Policies",
description = "Deactivating Policies",
key = "perm:policies:deactivate",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/manage"}
),
@Scope(
name = "Applying Changes on Policies",
description = "Applying Changes on Policies",
key = "perm:policies:changes",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/manage"}
),
@Scope(
name = "Updating the Policy Priorities",
description = "Updating the Policy Priorities",
key = "perm:policies:priorities",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/manage"}
),
@Scope(
name = "Fetching the Effective Policy",
description = "Fetching the Effective Policy",
key = "perm:policies:effective-policy",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/policies/view"}
)
}

@ -61,6 +61,7 @@ import javax.ws.rs.core.Response;
name = "Remote Session Connection",
description = "",
key = "perm:remote-session-service:connect",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/remote-session"}
)
}

@ -66,6 +66,7 @@ import java.util.List;
name = "Getting Details of Registered Devices",
description = "Getting Details of Registered Devices",
key = "perm:devices:view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
}

@ -53,48 +53,56 @@ import java.util.List;
name = "Getting the List of Roles",
description = "Getting the List of Roles",
key = "perm:roles:view",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/view"}
),
@Scope(
name = "Getting Permission Details of a Role",
description = "Getting Permission Details of a Role",
key = "perm:roles:permissions",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/view"}
),
@Scope(
name = "Getting the List of Roles",
description = "Getting the List of Roles",
key = "perm:roles:details",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/view"}
),
@Scope(
name = "Adding a Role",
description = "Adding a Role",
key = "perm:roles:add",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/manage"}
),
@Scope(
name = "Adding a combined Role",
description = "Adding a combined Role",
key = "perm:roles:create-combined-role",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/manage"}
),
@Scope(
name = "Updating Role Details",
description = "Updating Role Details",
key = "perm:roles:update",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/manage"}
),
@Scope(
name = "Deleting a Role",
description = "Deleting a Role",
key = "perm:roles:delete",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/manage"}
),
@Scope(
name = "Adding Users to a Role",
description = "Adding Users to a Role",
key = "perm:roles:add-users",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/roles/manage"}
)
}

@ -97,78 +97,91 @@ import javax.ws.rs.core.Response;
name = "Adding a User",
description = "Adding a User",
key = "perm:users:add",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/manage"}
),
@Scope(
name = "Getting Details of a User",
description = "Getting Details of a User",
key = "perm:users:details",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/view"}
),
@Scope(
name = "Updating Details of a User",
description = "Updating Details of a User",
key = "perm:users:update",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/manage"}
),
@Scope(
name = "Deleting a User",
description = "Deleting a User",
key = "perm:users:delete",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/manage"}
),
@Scope(
name = "Getting the Role Details of a User",
description = "Getting the Role Details of a User",
key = "perm:users:roles",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/view"}
),
@Scope(
name = "Getting Details of Users",
description = "Getting Details of Users",
key = "perm:users:user-details",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/view"}
),
@Scope(
name = "Getting the User Count",
description = "Getting the User Count",
key = "perm:users:count",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/view"}
),
@Scope(
name = "Getting the User existence status",
description = "Getting the User existence status",
key = "perm:users:is-exist",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/view"}
),
@Scope(
name = "Searching for a User Name",
description = "Searching for a User Name",
key = "perm:users:search",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/view"}
),
@Scope(
name = "Changing the User Password",
description = "Adding a User",
key = "perm:users:credentials",
roles = {"Internal/everyone"},
permissions = {"/login"}
),
@Scope(
name = "Sending Enrollment Invitations to Users",
description = "Sending Enrollment Invitations to Users",
key = "perm:users:send-invitation",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/users/manage"}
),
@Scope(
name = "Get activities",
description = "Get activities",
key = "perm:get-activity",
roles = {"Internal/everyone"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Getting the Permissions of the User",
description = "Getting the Permissions of the User",
key = "perm:user:permission-view",
roles = {"Internal/everyone"},
permissions = {"/login"}
)
}

@ -67,12 +67,14 @@ import javax.ws.rs.core.Response;
name = "Installing an Application (Internal API)",
description = "Installing an Application (Internal API)",
key = "perm:applications:install",
roles = {"admin"},
permissions = {"/device-mgt/applications/manage"}
),
@Scope(
name = "Uninstalling an Application (Internal API)",
description = "Uninstalling an Application (Internal API)",
key = "perm:applications:uninstall",
roles = {"admin"},
permissions = {"/device-mgt/applications/manage"}
)
}

@ -67,6 +67,7 @@ import javax.ws.rs.core.Response;
name = "Verify device authorization",
description = "Verify device authorization",
key = "perm:authorization:verify",
roles = {"admin"},
permissions = {"/device-mgt/authorization/verify"}
)
}

@ -57,6 +57,7 @@ import javax.ws.rs.core.Response;
name = "Devicetype deployment",
description = "Deploy devicetype",
key = "perm:devicetype:deployment",
roles = {"admin"},
permissions = {"/device-mgt/devicetype/deploy"}
)
}

@ -94,18 +94,21 @@ import java.util.List;
name = "Getting Details of a Device",
description = "Getting Details of a Device",
key = "perm:admin:devices:view",
roles = {"admin"},
permissions = {"/device-mgt/devices/owning-device/view"}
),
@Scope(
name = "Update the Device Owner",
description = "Update the ownership of the device",
key = "perm:admin:devices:update-enrollment",
roles = {"admin"},
permissions = {"/device-mgt/admin/devices/update-enrollment"}
),
@Scope(
name = "Permanently Delete the device specified by device id",
description = "Permanently Delete the device specified by device id",
key = "perm:devices:permanent-delete",
roles = {"admin"},
permissions = {"/device-mgt/admin/devices/permanent-delete"}
)
}

@ -92,18 +92,21 @@ import javax.ws.rs.core.Response;
name = "Manage a Device Type",
description = "Add, Edit or View a Device Type",
key = "perm:admin:device-type",
roles = {"admin"},
permissions = {"/device-mgt/admin/device-type"}
),
@Scope(
name = "Getting Details of a Device Type",
description = "Getting Details of a Device Type",
key = "perm:admin:device-type:view",
roles = {"admin"},
permissions = {"/device-mgt/admin/device-type/view"}
),
@Scope(
name = "Add Device Type Config",
description = "Add Platform Config of a Device Type",
key = "perm:admin:device-type:configs",
roles = {"admin"},
permissions = {"/device-mgt/admin/device-type/config"}
)
}

@ -70,18 +70,21 @@ import javax.ws.rs.core.Response;
name = "View groups",
description = "",
key = "perm:admin-groups:view",
roles = {"admin"},
permissions = {"/device-mgt/admin/groups/view"}
),
@Scope(
name = "Count groups",
description = "",
key = "perm:admin-groups:count",
roles = {"admin"},
permissions = {"/device-mgt/admin/groups/view"}
),
@Scope(
name = "Add groups",
description = "",
key = "perm:admin-groups:add",
roles = {"admin"},
permissions = {"/device-mgt/admin/groups/add"}
)
}

@ -53,12 +53,14 @@ import javax.ws.rs.core.Response;
name = "View Users",
description = "View Users",
key = "perm:admin-users:view",
roles = {"admin"},
permissions = {"/device-mgt/users/manage"}
),
@Scope(
name = "Delete Users Device Information",
description = "Delete users device details",
key = "perm:admin-users:remove",
roles = {"admin"},
permissions = {"/device-mgt/users/manage"}
)
}

@ -74,7 +74,6 @@ import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
import org.wso2.carbon.device.mgt.common.spi.OTPManagementService;
@ -549,16 +548,6 @@ public class DeviceMgtAPIUtils {
return searchManagerService;
}
public static PermissionManagerService getPermissionManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
PermissionManagerService PermissionManagerService =
(PermissionManagerService) ctx.getOSGiService(PermissionManagerService.class, null);
if (PermissionManagerService == null) {
throw new IllegalStateException("Permission manager service is not initialized.");
}
return PermissionManagerService;
}
public static GeoLocationProviderService getGeoService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
GeoLocationProviderService

@ -18,9 +18,6 @@
package org.wso2.carbon.device.mgt.common.permission.mgt;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* This class represents the information related to permission.
*/
@ -30,6 +27,7 @@ public class Permission {
private String path; // permission string
private String url; // url of the resource
private String method; // http method
private String urlPattern;
public String getUrl() {
return url;
@ -62,4 +60,12 @@ public class Permission {
public void setPath(String path) {
this.path = path;
}
public String getUrlPattern() {
return urlPattern;
}
public void setUrlPattern(String urlPattern) {
this.urlPattern = urlPattern;
}
}

@ -18,7 +18,7 @@
package org.wso2.carbon.device.mgt.common.permission.mgt;
import java.util.Properties;
import java.util.List;
/**
* This represents the Permission management functionality which should be implemented by
@ -26,22 +26,8 @@ import java.util.Properties;
*/
public interface PermissionManagerService {
/**
* Adds a permission.
*
* @param permission - Permission to be added
* @return A boolean indicating the status of the operation.
* @throws PermissionManagementException If some unusual behaviour is observed while adding the permission.
*/
boolean addPermission(Permission permission) throws PermissionManagementException;
boolean addPermission(String context, List<Permission> permissions) throws PermissionManagementException;
/**
* Fetches a given permission.
*
* @param properties - Properties of the permission to be fetched.
* @return The matched Permission object.
* @throws PermissionManagementException If some unusual behaviour is observed while fetching the permission.
*/
Permission getPermission(Properties properties) throws PermissionManagementException;
List<Permission> getPermission(String context) throws PermissionManagementException;
}

@ -42,6 +42,7 @@ public final class DeviceManagementConstants {
public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER";
public static final String DEVICE_CACHE = "DEVICE_CACHE";
public static final String API_RESOURCE_PERMISSION_CACHE = "API_RESOURCE_CACHE_CACHE";
public static final String GEOFENCE_CACHE = "GEOFENCE_CACHE";
public static final String ENROLLMENT_NOTIFICATION_API_ENDPOINT = "/api/device-mgt/enrollment-notification";
public static final String URL_SEPERATOR = "/";

@ -0,0 +1,64 @@
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.
*/
package org.wso2.carbon.device.mgt.core.cache;
import java.util.Objects;
public class APIResourcePermissionCacheKey {
private String context;
private volatile int hashCode;
public APIResourcePermissionCacheKey(String context) {
this.context = context;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!APIResourcePermissionCacheKey.class.isAssignableFrom(obj.getClass())) {
return false;
}
final APIResourcePermissionCacheKey other = (APIResourcePermissionCacheKey) obj;
String thisId = this.context;
String otherId = other.context;
if (!thisId.equals(otherId)) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Objects.hash(context);
}
return hashCode;
}
}

@ -0,0 +1,31 @@
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.
*/
package org.wso2.carbon.device.mgt.core.cache;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import java.util.List;
public interface APIResourcePermissionCacheManager {
void addAPIResourcePermissionToCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions);
void updateAPIResourcePermissionInCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions);
List<Permission> getAPIResourceRermissionFromCache(APIResourcePermissionCacheKey cacheKey);
}

@ -0,0 +1,84 @@
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.
*/
package org.wso2.carbon.device.mgt.core.cache.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheManager;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.cache.Cache;
import java.util.List;
public class APIResourcePermissionCacheManagerImpl implements APIResourcePermissionCacheManager {
private static final Log log = LogFactory.getLog(APIResourcePermissionCacheManagerImpl.class);
private static APIResourcePermissionCacheManagerImpl apiResourceCacgeManager;
private APIResourcePermissionCacheManagerImpl() {
}
public static APIResourcePermissionCacheManagerImpl getInstance() {
if (apiResourceCacgeManager == null) {
synchronized (APIResourcePermissionCacheManagerImpl.class) {
if (apiResourceCacgeManager == null) {
apiResourceCacgeManager = new APIResourcePermissionCacheManagerImpl();
}
}
}
return apiResourceCacgeManager;
}
@Override
public void addAPIResourcePermissionToCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions) {
Cache<APIResourcePermissionCacheKey, List<Permission>> lCache = DeviceManagerUtil.getAPIResourcePermissionCache();
if (lCache != null) {
if (lCache.containsKey(cacheKey)) {
this.updateAPIResourcePermissionInCache(cacheKey, permissions);
} else {
lCache.put(cacheKey, permissions);
}
}
}
@Override
public void updateAPIResourcePermissionInCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions) {
Cache<APIResourcePermissionCacheKey, List<Permission>> lCache = DeviceManagerUtil.getAPIResourcePermissionCache();
if (lCache != null) {
if (lCache.containsKey(cacheKey)) {
lCache.replace(cacheKey, permissions);
}
}
}
@Override
public List<Permission> getAPIResourceRermissionFromCache(APIResourcePermissionCacheKey cacheKey) {
Cache<APIResourcePermissionCacheKey, List<Permission>> lCache = DeviceManagerUtil.getAPIResourcePermissionCache();
if (lCache != null) {
return lCache.get(cacheKey);
}
return null;
}
}

@ -67,6 +67,7 @@ public class AnnotationProcessor {
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_DESCRIPTION = "description";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_KEY = "key";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_PERMISSIONS = "permissions";
private static final String SWAGGER_ANNOTATIONS_PROPERTIES_ROLES = "roles";
private static final String ANNOTATIONS_SCOPES = "scopes";
private static final String ANNOTATIONS_SCOPE = "scope";
private static final String DEFAULT_PERM_NAME = "default";
@ -239,6 +240,7 @@ public class AnnotationProcessor {
subCtx = makeContextURLReady(resourceRootContext) + makeContextURLReady(subCtx);
}
permission.setUrl(replaceDynamicPathVariables(subCtx));
permission.setUrlPattern(permission.getUrl().replace("*", "[a-zA-Z0-9-_]+"));
String httpMethod;
for (int i = 0; i < annotations.length; i++) {
httpMethod = getHTTPMethodAnnotation(annotations[i]);
@ -398,7 +400,7 @@ public class AnnotationProcessor {
if (scope != null) {
permission.setName(scope.getName());
//TODO: currently permission tree supports only adding one permission per API point.
permission.setPath(scope.getRoles().split(" ")[0]);
permission.setPath(scope.getPermissions().split(" ")[0]);
} else {
log.warn("No Scope mapping is done for scope key: " + scopeKey);
permission.setName(DEFAULT_PERM_NAME);
@ -420,8 +422,11 @@ public class AnnotationProcessor {
Scope scope;
String permissions[];
StringBuilder aggregatedPermissions;
String roles[];
StringBuilder aggregatedRoles;
for(int i=0; i<annotatedScopes.length; i++){
aggregatedPermissions = new StringBuilder();
aggregatedRoles = new StringBuilder();
methodHandler = Proxy.getInvocationHandler(annotatedScopes[i]);
scope = new Scope();
scope.setName(invokeMethod(scopeClass
@ -437,7 +442,14 @@ public class AnnotationProcessor {
aggregatedPermissions.append(permission);
aggregatedPermissions.append(" ");
}
scope.setRoles(aggregatedPermissions.toString());
scope.setPermissions(aggregatedPermissions.toString().trim());
roles = (String[])methodHandler.invoke(annotatedScopes[i], scopeClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_ROLES, null),null);
for (String role : roles) {
aggregatedRoles.append(role);
aggregatedRoles.append(",");
}
scope.setRoles(aggregatedRoles.toString().substring(0, aggregatedRoles.lastIndexOf(",")));
scopes.put(scope.getKey(), scope);
}
return scopes;

@ -21,6 +21,7 @@ public class Scope implements Serializable {
String key;
String name;
String roles;
String permissions;
String description;
int id;
@ -66,5 +67,13 @@ public class Scope implements Serializable {
public void setId(int id) {
this.id = id;
}
public String getPermissions() {
return permissions;
}
public void setPermissions(String permissions) {
this.permissions = permissions;
}
}

@ -62,11 +62,8 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener {
scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName());
List<Permission> permissions = annotationProcessor.extractPermissions(annotatedAPIClasses);
PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance();
if (permissions != null) {
for (Permission permission : permissions) {
permissionManagerService.addPermission(permission);
}
}
permissionManagerService.addPermission(contextPath, permissions);
} catch (PermissionManagementException e) {
log.error("Exception occurred while adding the permissions from webapp : "
+ servletContext.getContextPath(), e);

@ -22,11 +22,11 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
@ -48,6 +48,7 @@ import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.tenant.PlatformConfigurationManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.config.ui.UIConfigurationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
@ -75,7 +76,6 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceIm
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
import org.wso2.carbon.device.mgt.core.config.ui.UIConfigurationManager;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.DeviceMgtTenantMgtListener;

@ -18,13 +18,16 @@
package org.wso2.carbon.device.mgt.core.permission.mgt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey;
import org.wso2.carbon.device.mgt.core.cache.impl.APIResourcePermissionCacheManagerImpl;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* This class will add, update custom permissions defined in permission.xml in webapps and it will
@ -32,10 +35,7 @@ import java.util.Set;
*/
public class PermissionManagerServiceImpl implements PermissionManagerService {
public static final String URL_PROPERTY = "URL";
public static final String HTTP_METHOD_PROPERTY = "HTTP_METHOD";
private static PermissionManagerServiceImpl registryBasedPermissionManager;
private static PermissionTree permissionTree; // holds the permissions at runtime.
private PermissionManagerServiceImpl() {
}
@ -45,7 +45,6 @@ public class PermissionManagerServiceImpl implements PermissionManagerService {
synchronized (PermissionManagerServiceImpl.class) {
if (registryBasedPermissionManager == null) {
registryBasedPermissionManager = new PermissionManagerServiceImpl();
permissionTree = new PermissionTree();
}
}
}
@ -53,21 +52,22 @@ public class PermissionManagerServiceImpl implements PermissionManagerService {
}
@Override
public boolean addPermission(Permission permission) throws PermissionManagementException {
// adding a permission to the tree
permission.setPath(permission.getPath());
permissionTree.addPermission(permission);
return PermissionUtils.putPermission(permission);
public boolean addPermission(String context, List<Permission> permissions) throws PermissionManagementException {
try {
for (Permission permission : permissions) {
PermissionUtils.putPermission(permission);
}
APIResourcePermissionCacheManagerImpl.getInstance().addAPIResourcePermissionToCache(
new APIResourcePermissionCacheKey(context), permissions);
} catch (PermissionManagementException e) {
return false;
}
return true;
}
@Override
public Permission getPermission(Properties properties) throws PermissionManagementException {
String url = (String) properties.get(URL_PROPERTY);
String httpMethod = (String) properties.get(HTTP_METHOD_PROPERTY);
if (url == null || url.isEmpty() || httpMethod == null || httpMethod.isEmpty()) {
throw new PermissionManagementException("Resource URI/HTTP method is empty");
}
return permissionTree.getPermission(url, httpMethod);
public List<Permission> getPermission(String context) throws PermissionManagementException {
return APIResourcePermissionCacheManagerImpl.getInstance().getAPIResourceRermissionFromCache(
new APIResourcePermissionCacheKey(context));
}
}

@ -73,8 +73,10 @@ import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey;
import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
import org.wso2.carbon.device.mgt.core.cache.GeoCacheKey;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@ -136,6 +138,7 @@ public final class DeviceManagerUtil {
public static final String GENERAL_CONFIG_RESOURCE_PATH = "general";
private static boolean isDeviceCacheInitialized = false;
private static boolean isAPIResourcePermissionCacheInitialized = false;
private static boolean isGeoFenceCacheInitialized = false;
public static Document convertToDocument(File file) throws DeviceManagementException {
@ -663,6 +666,44 @@ public final class DeviceManagerUtil {
}
}
public static void initializeAPIResourcePermissionCache() {
// DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
// int deviceCacheExpiry = config.getDeviceCacheConfiguration().getExpiryTime();
// long deviceCacheCapacity = config.getDeviceCacheConfiguration().getCapacity();
CacheManager manager = getCacheManager();
// if (config.getDeviceCacheConfiguration().isEnabled()) {
if(!isDeviceCacheInitialized) {
isDeviceCacheInitialized = true;
if (manager != null) {
// if (deviceCacheExpiry > 0) {
// manager.<DeviceCacheKey, Device>createCacheBuilder(DeviceManagementConstants.DEVICE_CACHE).
// setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
// deviceCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
// Duration(TimeUnit.SECONDS, deviceCacheExpiry)).setStoreByValue(true).build();
// if(deviceCacheCapacity > 0 ) {
// ((CacheImpl) manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE)).
// setCapacity(deviceCacheCapacity);
// }
// } else {
manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE);
// }
} else {
// if (deviceCacheExpiry > 0) {
// Caching.getCacheManager().
// <DeviceCacheKey, Device>createCacheBuilder(DeviceManagementConstants.DEVICE_CACHE).
// setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
// deviceCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
// Duration(TimeUnit.SECONDS, deviceCacheExpiry)).setStoreByValue(true).build();
// ((CacheImpl)(manager.<DeviceCacheKey, Device>getCache(DeviceManagementConstants.DEVICE_CACHE))).
// setCapacity(deviceCacheCapacity);
// } else {
Caching.getCacheManager().<DeviceCacheKey, Device>getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE);
// }
}
}
// }
}
/**
* Enable Geofence caching according to the configurations proviced by cdm-config.xml
*/
@ -722,6 +763,24 @@ public final class DeviceManagerUtil {
return deviceCache;
}
public static Cache<APIResourcePermissionCacheKey, List<Permission>> getAPIResourcePermissionCache() {
// DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
CacheManager manager = getCacheManager();
Cache<APIResourcePermissionCacheKey, List<Permission>> apiResourcePermissionCache = null;
// if (config.getDeviceCacheConfiguration().isEnabled()) {
if(!isAPIResourcePermissionCacheInitialized) {
initializeAPIResourcePermissionCache();
}
if (manager != null) {
apiResourcePermissionCache = manager.getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE);
} else {
apiResourcePermissionCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER)
.getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE);
}
// }
return apiResourcePermissionCache;
}
/**
* Get geofence cache object
* @return {@link Cache<GeoCacheKey, GeofenceData>}

@ -232,18 +232,18 @@ public class JWTClientUtil {
}
List<String> aud = jwtConfig.getAudiences();
//set up the basic claims
JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setIssueTime(new Date(iat));
claimsSet.setExpirationTime(new Date(exp));
claimsSet.setIssuer(iss);
claimsSet.setSubject(username);
claimsSet.setNotBeforeTime(new Date(nbf));
claimsSet.setJWTID(jti);
claimsSet.setAudience(aud);
claimsSet.setClaim(SIGNED_JWT_AUTH_USERNAME, username);
JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
claimsSet.issueTime(new Date(iat));
claimsSet.expirationTime(new Date(exp));
claimsSet.issuer(iss);
claimsSet.subject(username);
claimsSet.notBeforeTime(new Date(nbf));
claimsSet.jwtID(jti);
claimsSet.audience(aud);
claimsSet.claim(SIGNED_JWT_AUTH_USERNAME, username);
if (customClaims != null && !customClaims.isEmpty()) {
for (String key : customClaims.keySet()) {
claimsSet.setClaim(key, customClaims.get(key));
claimsSet.claim(key, customClaims.get(key));
}
}
@ -280,7 +280,7 @@ public class JWTClientUtil {
}
}
JWSSigner signer = new RSASSASigner(rsaPrivateKey);
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet.build());
signedJWT.sign(signer);
String assertion = signedJWT.serialize();
return assertion;

@ -64,6 +64,7 @@ import javax.ws.rs.core.Response;
name = "View configurations",
description = "",
key = "perm:sms-handler:view-configuration",
roles = {"Internal/everyone"},
permissions = {"/sms-handler/platform-configurations/view"}
)
})

@ -55,22 +55,22 @@
org.wso2.carbon.webapp.authenticator.framework.*
</Export-Package>
<Import-Package>
com.nimbusds.jose,
com.nimbusds.jose.crypto,
com.nimbusds.jwt,
com.nimbusds.jose;version="${nimbus.orbit.version.range}",
com.nimbusds.jose.crypto;version="${nimbus.orbit.version.range}",
com.nimbusds.jwt;version="${nimbus.orbit.version.range}",
javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
javax.xml.validation,
<!--org.apache.catalina,-->
<!--org.apache.catalina.connector,-->
<!--org.apache.catalina.util,-->
org.apache.catalina;version="9.0",
org.apache.catalina.connector;version="9.0",
org.apache.catalina.util;version="9.0",
org.apache.commons.logging,
<!--org.apache.coyote,-->
<!--org.apache.tomcat.util.buf,-->
<!--org.apache.tomcat.util.http,-->
org.osgi.service.component,
org.osgi.framework,
org.apache.coyote;version="9.0",
org.apache.tomcat.util.buf;version="9.0",
org.apache.tomcat.util.http;version="9.0",
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.w3c.dom,
org.wso2.carbon.context,
org.wso2.carbon.core.util,
@ -85,15 +85,15 @@
org.wso2.carbon.utils,
org.wso2.carbon.utils.multitenancy,
org.xml.sax,
com.google.gson.*,
<!--com.google.gson.*,-->
javax.servlet,
javax.servlet.http,
javax.xml,
org.apache.axis2.transport.http,
org.wso2.carbon.certificate.mgt.core.*,
org.wso2.carbon.device.mgt.core.permission.mgt,
org.wso2.carbon.device.mgt.core.permission.mgt.*,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common.permission.mgt,
org.wso2.carbon.device.mgt.common.permission.mgt.*,
org.apache.axis2,
org.apache.axis2.client,
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",
@ -114,6 +114,9 @@
org.wso2.carbon.base,
org.owasp.encoder
</Import-Package>
<!--<Embed-Dependency>-->
<!--tomcat-coyote,-->
<!--</Embed-Dependency>-->
</instructions>
</configuration>
</plugin>
@ -194,6 +197,22 @@
<dependency>
<groupId>org.wso2.carbon.identity.inbound.auth.oauth2</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
<exclusions>
<exclusion>
<!--<dependency>-->
<groupId>org.wso2.orbit.com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<!--</dependency>-->
</exclusion>
<exclusion>
<!--<dependency>-->
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<!--<version>9.10</version>-->
<!--</dependency>-->
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
@ -202,6 +221,7 @@
<dependency>
<groupId>org.wso2.orbit.com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>

@ -73,7 +73,7 @@ public class AuthenticationFrameworkUtil {
}
}
static boolean isUserAuthorized(int tenantId, String tenantDomain, String username, String
public static boolean isUserAuthorized(int tenantId, String tenantDomain, String username, String
permission) throws
AuthenticationException {
boolean tenantFlowStarted = false;

@ -18,11 +18,9 @@
*/
package org.wso2.carbon.webapp.authenticator.framework;
import com.google.gson.Gson;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.encoder.Encode;
@ -33,6 +31,7 @@ import org.wso2.carbon.user.api.Tenant;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.PermissionAuthorizer;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.WebappTenantAuthorizer;
import javax.servlet.http.HttpServletResponse;
@ -48,9 +47,6 @@ public class WebappAuthenticationValve extends CarbonTomcatValve {
private static final Log log = LogFactory.getLog(WebappAuthenticationValve.class);
private static final TreeMap<String, String> nonSecuredEndpoints = new TreeMap<>();
private static final String PERMISSION_PREFIX = "/permission/admin";
public static final String AUTHORIZE_PERMISSION = "Authorize-Permission";
private static InetAddress inetAddress = null;
@Override
@ -81,8 +77,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve {
}
}
if ((this.isContextSkipped(request) || this.skipAuthentication(request))
&& (StringUtils.isEmpty(request.getHeader(AUTHORIZE_PERMISSION)))) {
if ((this.isContextSkipped(request) || this.skipAuthentication(request))) {
this.getNext().invoke(request, response, compositeValve);
return;
}
@ -103,29 +98,12 @@ public class WebappAuthenticationValve extends CarbonTomcatValve {
// This section will allow to validate a given access token is authenticated to access given
// resource(permission)
if (request.getCoyoteRequest() != null
&& StringUtils.isNotEmpty(request.getHeader(AUTHORIZE_PERMISSION))
&& (authenticationInfo.getStatus() == WebappAuthenticator.Status.CONTINUE ||
authenticationInfo.getStatus() == WebappAuthenticator.Status.SUCCESS)) {
boolean isAllowed;
try {
isAllowed = AuthenticationFrameworkUtil.isUserAuthorized(
authenticationInfo.getTenantId(), authenticationInfo.getTenantDomain(),
authenticationInfo.getUsername(),
PERMISSION_PREFIX + request.getHeader (AUTHORIZE_PERMISSION));
} catch (AuthenticationException e) {
String msg = "Could not authorize permission";
log.error(msg);
AuthenticationFrameworkUtil.handleResponse(request, response,
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
return;
}
if (isAllowed) {
Gson gson = new Gson();
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_OK,
gson.toJson(authenticationInfo));
return;
} else {
WebappAuthenticator.Status authorizeStatus = PermissionAuthorizer.authorize(request, authenticationInfo);
isAllowed = WebappAuthenticator.Status.SUCCESS == authorizeStatus;
if (!isAllowed) {
log.error("Unauthorized message from user " + authenticationInfo.getUsername());
AuthenticationFrameworkUtil.handleResponse(request, response,
HttpServletResponse.SC_FORBIDDEN, "Unauthorized to access the API");
@ -133,7 +111,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve {
}
}
Tenant tenant = null;
Tenant tenant = null;
if (authenticationInfo.getTenantId() != -1) {
try {
PrivilegedCarbonContext.startTenantFlow();

@ -0,0 +1,30 @@
package org.wso2.carbon.webapp.authenticator.framework.authorizer;
/**
* Created by amalka on 6/26/21.
*/
public class MatchingResource {
private String urlPattern;
private String permission;
public MatchingResource(String urlPattern, String permission) {
this.urlPattern = urlPattern;
this.permission = permission;
}
public String getUrlPattern() {
return urlPattern;
}
public void setUrlPattern(String urlPattern) {
this.urlPattern = urlPattern;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
}

@ -0,0 +1,143 @@
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.
*/
package org.wso2.carbon.webapp.authenticator.framework.authorizer;
import org.apache.catalina.connector.Request;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class PermissionAuthorizer {
private static final Log log = LogFactory.getLog(PermissionAuthorizer.class);
public static WebappAuthenticator.Status authorize(Request request, AuthenticationInfo authenticationInfo) {
String requestUri = request.getRequestURI();
String requestMethod = request.getMethod();
String context = request.getContextPath();
if (requestUri == null || requestUri.isEmpty() || requestMethod == null || requestMethod.isEmpty()) {
return WebappAuthenticator.Status.CONTINUE;
}
PermissionManagerService registryBasedPermissionManager =
PermissionManagerServiceImpl.getInstance();
List<Permission> matchingPermissions = null;
try {
matchingPermissions = registryBasedPermissionManager.getPermission(context);
} catch (PermissionManagementException e) {
log.error(
"Error occurred while fetching the permission for URI : " + requestUri +
", msg = " + e.getMessage());
}
if (matchingPermissions == null) {
if (log.isDebugEnabled()) {
log.debug("Permission to request '" + requestUri + "' is not defined in the configuration");
}
return WebappAuthenticator.Status.FAILURE;
}
String requiredPermission = null;
List<MatchingResource> matchingResources = new ArrayList<>();
for (Permission permission : matchingPermissions) {
if (requestMethod.equals(permission.getMethod()) && requestUri.matches(permission.getUrlPattern())) {
if (requestUri.equals(permission.getUrl())) { // is there a exact match
requiredPermission = permission.getPath();
break;
} else { // all templated urls add to a list
matchingResources.add(new MatchingResource(permission.getUrlPattern().replace(context, ""), permission.getPath()));
}
}
}
if (requiredPermission == null) {
if (matchingResources.size() == 1) { // only 1 templated url found
requiredPermission = matchingResources.get(0).getPermission();
}
if (matchingResources.size() > 1) { // more than 1 templated urls found
String urlWithoutContext = requestUri.replace(context, "");
StringTokenizer st = new StringTokenizer(urlWithoutContext, "/");
int tokenPosition = 1;
while (st.hasMoreTokens()) {
List<MatchingResource> tempList = new ArrayList<>();
String currentToken = st.nextToken();
for (MatchingResource matchingResource : matchingResources) {
StringTokenizer stmr = new StringTokenizer(matchingResource.getUrlPattern(), "/");
int internalTokenPosition = 1;
while (stmr.hasMoreTokens()) {
String internalToken = stmr.nextToken();
if ((tokenPosition == internalTokenPosition) && currentToken.equals(internalToken)) {
tempList.add(matchingResource);
}
internalTokenPosition++;
if (tokenPosition < internalTokenPosition) {
break;
}
}
}
if (tempList.size() == 1) {
requiredPermission = tempList.get(0).getPermission();
break;
}
tokenPosition++;
}
}
}
if (requiredPermission == null) {
if (log.isDebugEnabled()) {
log.debug("Matching permission not found for " + requestUri);
}
return WebappAuthenticator.Status.FAILURE;
}
boolean isUserAuthorized;
try {
isUserAuthorized = AuthenticationFrameworkUtil.isUserAuthorized(
authenticationInfo.getTenantId(), authenticationInfo.getTenantDomain(),
authenticationInfo.getUsername(), requiredPermission);
} catch (AuthenticationException e) {
log.error("Error occurred while retrieving user store. " + e.getMessage());
return WebappAuthenticator.Status.FAILURE;
}
if (isUserAuthorized) {
return WebappAuthenticator.Status.SUCCESS;
} else {
return WebappAuthenticator.Status.FAILURE;
}
}
}

@ -2175,8 +2175,8 @@
<eclipse.paho.version>1.0.2</eclipse.paho.version>
<!-- Nimbus Jose-->
<nimbus.orbit.version>2.26.1.wso2v3</nimbus.orbit.version>
<nimbus.orbit.version.range>[2.26.1, 3.0.0)</nimbus.orbit.version.range>
<nimbus.orbit.version>7.3.0.wso2v1</nimbus.orbit.version>
<nimbus.orbit.version.range>[7.3, 8)</nimbus.orbit.version.range>
<!--javax ws rs version-->
<javax.ws.rs.version>2.0.1</javax.ws.rs.version>

Loading…
Cancel
Save