use of org.wso2.charon3.core.objects.Role in project airavata by apache.
the class DefaultAiravataSecurityManager method isUserAuthorized.
public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException {
try {
String subject = authzToken.getClaimsMap().get(Constants.USER_NAME);
String accessToken = authzToken.getAccessToken();
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String action = metaData.get(Constants.API_METHOD_NAME);
// if the authz cache is enabled, check in the cache if the authz decision is cached and if so, what the status is
if (ServerSettings.isAuthzCacheEnabled()) {
// obtain an instance of AuthzCacheManager implementation.
AuthzCacheManager authzCacheManager = AuthzCacheManagerFactory.getAuthzCacheManager();
// check in the cache
AuthzCachedStatus authzCachedStatus = authzCacheManager.getAuthzCachedStatus(new AuthzCacheIndex(subject, gatewayId, accessToken, action));
if (AuthzCachedStatus.AUTHORIZED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
return true;
} else if (AuthzCachedStatus.NOT_AUTHORIZED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
return false;
} else if (AuthzCachedStatus.NOT_CACHED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is not in the cache. " + "Obtaining it from the authorization server.");
CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
String username = credential.getLoginUserName();
if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
username = username + "@" + gwrp.getIdentityServerTenant();
String password = credential.getPassword();
// talk to Authorization Server, obtain the decision, cache it and return the result.
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
// initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
TrustStoreManager trustStoreManager = new TrustStoreManager();
trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
if (validationResponse.getValid()) {
String authorizedUserName = validationResponse.getAuthorizedUser();
if (authorizedUserName.contains("@")) {
authorizedUserName = authorizedUserName.split("@")[0];
}
if (subject.contains("@")) {
subject = subject.split("@")[0];
}
// cannot impersonate users
if (!authorizedUserName.toLowerCase().equals(subject.toLowerCase()))
return false;
long expiryTimestamp = validationResponse.getExpiryTime();
// check for fine grained authorization for the API invocation, based on XACML.
DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
// cache the authorization decision
authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), new AuthzCacheEntry(authorizationDecision, expiryTimestamp, System.currentTimeMillis()));
return authorizationDecision;
} else {
return false;
}
} else {
// undefined status returned from the authz cache manager
throw new AiravataSecurityException("Error in reading from the authorization cache.");
}
} else {
CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
String username = credential.getLoginUserName();
if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
username = username + "@" + gwrp.getIdentityServerTenant();
String password = credential.getPassword();
// talk to Authorization Server, obtain the decision and return the result (authz cache is not enabled).
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
// initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
TrustStoreManager trustStoreManager = new TrustStoreManager();
trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
boolean isOAuthTokenValid = validationResponse.getValid();
// if XACML based authorization is enabled, check for role based authorization for the API invocation
DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
return (isOAuthTokenValid && authorizationDecision);
}
} catch (AxisFault axisFault) {
logger.error(axisFault.getMessage(), axisFault);
throw new AiravataSecurityException("Error in initializing the configuration context for creating the OAuth validation client.");
} catch (ApplicationSettingsException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in reading OAuth server configuration.");
} catch (RegistryServiceException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in accessing AppCatalog.");
} catch (TException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in connecting to Credential Store Service.");
}
}
use of org.wso2.charon3.core.objects.Role in project core-util by WSO2Telco.
the class WSO2PermissionBuilder method build.
/**
* This will build the permision tree using given users name
*/
public Map<String, Object> build(final String userName) throws BusinessException {
Map<String, Object> permisionTree = Collections.emptyMap();
RetunEntitiy retunItem = new RetunEntitiy();
try {
UserRoleProsser userRoleRetriever = new UserRoleProsser();
UIPermissionNode uiPermissionTree = null;
List<String> currentUserRoleList = userRoleRetriever.getRolesByUserName(userName);
/**
* None of the roles are assign for the user
*/
if (currentUserRoleList.isEmpty()) {
throw new BusinessException("No roles assigned for user :" + userName);
}
for (Iterator<String> iterator = currentUserRoleList.iterator(); iterator.hasNext(); ) {
String roleName = iterator.next();
UIPermissionNode rolePermissions = userAdminStub.getRolePermissions(roleName);
/**
* if the permission node is empty
*/
if (rolePermissions == null || rolePermissions.getNodeList() == null) {
continue;
}
/**
* filter out ui permission only
*/
Optional<UIPermissionNode> optNode = Arrays.stream(rolePermissions.getNodeList()).filter(rowItem -> rowItem.getDisplayName().equalsIgnoreCase(UserRolePermissionType.UI_PERMISSION.getTObject())).findFirst();
/**
* check for existence of node
*/
if (optNode.isPresent()) {
uiPermissionTree = optNode.get();
if (uiPermissionTree.getNodeList() != null && uiPermissionTree.getNodeList().length > 0) {
retunItem = popUserRolePermissions(uiPermissionTree.getNodeList());
if (retunItem.atLeastOneSelected) {
break;
}
} else {
/**
* if the current role does not contain Ui permission then continue
*/
continue;
}
}
}
if (retunItem.returnMap.isEmpty()) {
throw new BusinessException(UserRolePermissionType.UI_PERMISSION.getTObject() + " not assigned for the user :" + userName + " , assigned roles :[ " + StringUtils.join(currentUserRoleList, ",") + "]");
}
} catch (RemoteException | UserAdminUserAdminException e) {
log.error("UIPermission.build", e);
throw new BusinessException(GenaralError.INTERNAL_SERVER_ERROR);
}
if (retunItem.returnMap.isEmpty()) {
log.warn(" No ui permission tree found for " + userName);
return Collections.emptyMap();
} else {
return retunItem.returnMap;
}
}
use of org.wso2.charon3.core.objects.Role in project charon by wso2.
the class PatchOperationUtil method doPatchReplaceOnPathWithoutFiltersForLevelOne.
/*
* This performs patch on resource based on the path value.No filter is specified here.
* And this is for level one attributes.
* @param oldResource
* @param schema
* @param decoder
* @param operation
* @param attributeParts
* @throws BadRequestException
* @throws CharonException
* @throws JSONException
* @throws InternalErrorException
*/
private static void doPatchReplaceOnPathWithoutFiltersForLevelOne(AbstractSCIMObject oldResource, SCIMResourceTypeSchema schema, JSONDecoder decoder, PatchOperation operation, String[] attributeParts) throws BadRequestException, CharonException, InternalErrorException {
Attribute attribute = oldResource.getAttribute(attributeParts[0]);
if (attribute != null) {
if (!attribute.getType().equals(SCIMDefinitions.DataType.COMPLEX)) {
if (!attribute.getMultiValued()) {
if (attribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY) || attribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE)) {
throw new BadRequestException("Can not replace a immutable attribute or a read-only attribute", ResponseCodeConstants.MUTABILITY);
} else {
((SimpleAttribute) attribute).setValue(operation.getValues().toString());
}
} else {
if (attribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY) || attribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE)) {
throw new BadRequestException("Can not replace a immutable attribute or a read-only attribute", ResponseCodeConstants.MUTABILITY);
} else {
((MultiValuedAttribute) attribute).deletePrimitiveValues();
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(operation.getValues());
} catch (JSONException e) {
throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
((MultiValuedAttribute) attribute).setAttributePrimitiveValue(jsonArray.get(i));
} catch (JSONException e) {
throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
}
}
}
}
} else {
if (attribute.getMultiValued()) {
if (attribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY) || attribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE)) {
throw new BadRequestException("Can not replace a immutable attribute or a read-only attribute", ResponseCodeConstants.MUTABILITY);
} else {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(new JSONTokener(operation.getValues().toString()));
} catch (JSONException e) {
throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
}
AttributeSchema attributeSchema = SchemaUtil.getAttributeSchema(attribute.getName(), schema);
MultiValuedAttribute newMultiValuedAttribute = decoder.buildComplexMultiValuedAttribute(attributeSchema, jsonArray);
oldResource.deleteAttribute(attribute.getName());
oldResource.setAttribute(newMultiValuedAttribute);
}
} else {
if (attribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY) || attribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE)) {
throw new BadRequestException("Can not replace a immutable attribute or a read-only attribute", ResponseCodeConstants.MUTABILITY);
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(new JSONTokener(operation.getValues().toString()));
} catch (JSONException e) {
throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
}
AttributeSchema attributeSchema = SchemaUtil.getAttributeSchema(attribute.getName(), schema);
ComplexAttribute newComplexAttribute = null;
try {
newComplexAttribute = decoder.buildComplexAttribute(attributeSchema, jsonObject);
} catch (JSONException e) {
throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
}
oldResource.deleteAttribute(attribute.getName());
oldResource.setAttribute(newComplexAttribute);
}
}
}
} else {
// Check whether the patched attributes are permissions of Roles.
if (schema.isSchemaAvailable(SCIMConstants.ROLE_SCHEMA_URI) && SCIMConstants.RoleSchemaConstants.PERMISSIONS.equalsIgnoreCase(attributeParts[0])) {
JSONArray permissionsJSONArray = getJsonArray(operation);
// Assign permissions to the Role.
if (oldResource instanceof Role) {
((Role) oldResource).setPermissions(decoder.toList(permissionsJSONArray));
}
}
// Create and add the attribute.
createAttributeOnResourceWithPathWithoutFiltersForLevelOne(oldResource, schema, decoder, operation, attributeParts);
}
}
use of org.wso2.charon3.core.objects.Role in project charon by wso2.
the class RoleResourceManager method processRoleList.
/**
* Method to process a list and return a SCIM response.
*
* @param roleList Filtered role list.
* @param encoder Json encoder.
* @param startIndex Starting index.
* @return SCIM response.
* @throws CharonException CharonException.
* @throws BadRequestException BadRequestException.
*/
private SCIMResponse processRoleList(List<Object> roleList, JSONEncoder encoder, int startIndex) throws CharonException, BadRequestException {
int totalResults = 0;
if (roleList == null) {
roleList = Collections.emptyList();
} else {
if (roleList.size() >= 1) {
if (roleList.get(0) instanceof Integer) {
totalResults = (int) roleList.get(0);
roleList.remove(0);
} else {
if (logger.isDebugEnabled()) {
logger.debug("First element in the list is not an int. Setting result count as: " + roleList.size());
}
totalResults = roleList.size();
}
}
}
for (Object role : roleList) {
ServerSideValidator.validateSCIMObjectForRequiredAttributes((Role) role, SCIMSchemaDefinitions.SCIM_ROLE_SCHEMA);
}
// Create a listed resource object out of the returned groups list.
ListedResource listedResource = createListedResource(roleList, startIndex, totalResults);
// Convert the listed resource into specific format.
String encodedListedResource = encoder.encodeSCIMObject(listedResource);
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedListedResource, responseHeaders);
}
use of org.wso2.charon3.core.objects.Role in project charon by wso2.
the class RoleResourceManager method listWithPOSTRole.
@Override
public SCIMResponse listWithPOSTRole(String searchRequest, RoleManager roleManager) {
try {
if (roleManager == null) {
String error = "Provided role manager is null.";
throw new InternalErrorException(error);
}
JSONEncoder encoder = getEncoder();
JSONDecoder decoder = getDecoder();
SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getRoleResourceSchema();
// Create the search request object.
SearchRequest searchRequestObject = decoder.decodeSearchRequestBody(searchRequest, schema);
searchRequestObject.setCount(ResourceManagerUtil.processCount(searchRequestObject.getCountStr()));
searchRequestObject.setStartIndex(ResourceManagerUtil.processStartIndex(searchRequestObject.getStartIndexStr()));
if (searchRequestObject.getSchema() != null && !searchRequestObject.getSchema().equals(SCIMConstants.SEARCH_SCHEMA_URI)) {
throw new BadRequestException("Provided schema is invalid.", ResponseCodeConstants.INVALID_VALUE);
}
// Check whether provided sortOrder is valid or not.
if (searchRequestObject.getSortOder() != null) {
if (!(searchRequestObject.getSortOder().equalsIgnoreCase(SCIMConstants.OperationalConstants.ASCENDING) || searchRequestObject.getSortOder().equalsIgnoreCase(SCIMConstants.OperationalConstants.DESCENDING))) {
String error = " Invalid sortOrder value is specified";
throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE);
}
}
// ascending.
if (searchRequestObject.getSortOder() == null && searchRequestObject.getSortBy() != null) {
searchRequestObject.setSortOder(SCIMConstants.OperationalConstants.ASCENDING);
}
List<Object> rolesList = roleManager.listRolesWithPost(searchRequestObject);
int totalResults = (int) rolesList.get(0);
rolesList.remove(0);
List<Object> returnedRoles = rolesList;
for (Object role : returnedRoles) {
ServerSideValidator.validateRetrievedSCIMObjectInList((Role) role, schema, searchRequestObject.getAttributesAsString(), searchRequestObject.getExcludedAttributesAsString());
}
// Create a listed resource object out of the returned users list.
ListedResource listedResource = createListedResource(returnedRoles, searchRequestObject.getStartIndex(), totalResults);
String encodedListedResource = encoder.encodeSCIMObject(listedResource);
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedListedResource, responseHeaders);
} catch (CharonException | InternalErrorException | BadRequestException | NotImplementedException e) {
return AbstractResourceManager.encodeSCIMException(e);
}
}
Aggregations